Reputation: 2280
This is my code:
const char readArr[] = readWord.c_str();
This gives an error: array initializer must be an initializer list or string literal
Why must I use
const char *readArr = readWord.c_str();?
Upvotes: 0
Views: 164
Reputation: 1233
const char readArr[] = readWord.c_str();
The reason this is not legal is that it simply doesn't make sense to initialise an array from a pointer. A pointer is in essence a memory address: it points to some data, whether that data is dynamically or statically allocated (allocated 'on the heap' or 'on the stack' respectively). A pointer does not record how much memory is there.
This is confusing to newcomers to C and C++ because the language often allows you to treat arrays as if they were just pointers to their first element. That doesn't mean that arrays are just pointers to their first element. They aren't. But if you use them in an expression they will decay to a pointer to their first element.
Upvotes: 1
Reputation: 1342
Because arrays are not pointers. An array... is an array, period. char readArr[]
(just like char arr[4]
) declares something directly in the local memory space (the stack, for a function) so that something has to be statically allocated.
str.c_str() is somewhere on the heap so that can't work.
Upvotes: 0
Reputation: 118350
It's for the same reason you can't
const char *p="foo";
const char readArr[]=p;
either. An array is not a discrete object that can be initialized. The only thing that can be initialized in C++ is a discrete object, and an array is not an object per se. An array is a conceptual address of a contiguous list of values, in consecutive memory locations. When an array is used in an expression, such as:
readArr[i]
The array's name decays to a pointer to the first element in the array. Now, guess what you did when you wrote this:
const char *readArr = readWord.c_str();
Well, you just stored a pointer to the first element in an array of characters, that's owned by the readWord
std::string
.
In a regular array declaration:
char readArr[]="Hello";
the compiler is given the length of the string, and thus it initialize a consecutive list of character values, and the label readArr
to it.
Upvotes: 2