I am trying to store an array of characters on the heap.
The following code works
char *array[3];
*array = new char;
And also the following
char *array[3];
array[0] = new char;
But not the following
char *array[3];
array = new char;
I viewed the contents of *array
, array[0]
and array
. The first and second do not contain valid pointer addresses after assigning using new
but the third one does. So what makes the third one not work? How do the other two work while they just seem to store some unknown symbols (such as $,%,-) rather than the actual address of the pointer?
Perhaps it will help to elaborate what a char *array[3]
is. This is an array of three pointers, which point to characters. That is, array[0]
, array[1]
, and array[2]
are each pointers to a character. So, *array
and array[0]
are fine places (and in fact the same place) to store a pointer to a character, but array
isn't even a pointer, it is an array, so trying to store a pointer there doesn't make sense.
If you want to store characters in the heap (using a c-style array of characters), you should just do char *array;
and then initialize it as array = new char[3];
However, since you are using C++, it is recommended you either use std::string
if you are trying to store a string, or std::vector
if you want a list of single characters.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.