Yes, you have to dynamically allocate space for your array. Space allocated in this way must be deleted afterward, so to properly create/delete a c-string, you would do this:
1 2 3 4 5 6 7 8 9 10 11
char* str; // make a char pointer
int i;
cout << "How big do you want: ";
cin >> i;
// Allocate space
str = newchar[i]; // notice that i isn't a constant
// Use the array as needed
delete [] str; // Delete the string when done
Of course you don't want to ask someone how long their name is. The trick here is to provide a c-string much longer than necessary (1000 rather than 100), and then remove it from scope:
#include <iostream>
usingnamespace std;
constchar* getName();
int main(void)
{
constchar* name = getName();
cout << "Hi " << name;
delete [] name;
cin.get();
return 0;
}
// While oldName is very long, a newName is made to be just the right length.
// newName is returned and oldName goes out of scope.
constchar* getName()
{
char oldName[1000]; // very long
cout << "What is your name: ";
cin.getline(oldName, 999);
char * newName = newchar[strlen(oldName) + 1];
strcpy(newName, oldName);
return newName;
}
The "C way" of doing what LowestOne posted is by using malloc() / calloc() and free() instead of new[] and delete[].
Otherwise, remember that std::string has the c_str() member function which returns the C-compatible pointer to an array of characters, '\0'-terminated.