Pointers's pointer c++ char initialization
I'm with a doubt In initialization of this in C++:
char** A_Function()
{
char** charList = new char*[2];
charList[0] = "abcde";
charList[1] = "fghij";
return charList;
}
There's no problem "on compiling this co开发者_Python百科de", but I'm not sure about the behaviour.
1 - the char list: char* is on heap ok? 2 - the charList[n_position] is on heap or stack?
I don't understand what char*[2] realy means, does it mean: Its a static array that have on each of its element a pointer to a char?
If it is static this array will be allocated on stack, so this array is a huge bug maker?
If I'm right, how to allocate it on heap?
Maybe a picture would help:
When you return from the A_Function
, charList
gets destroyed, but the other two remain intact. Since you're returning the value of charList
from A_Function
there's no problem -- you're just going to have that same value held in a different variable, at least assuming you actually use the return value from A_Function
(i.e., assign it to something).
If you don't keep that value, you have a memory leak -- you'll no longer have a pointer to the array of two pointers you allocated on the free store, so you won't be able to free them.
The array of 2 pointers of char *
type is allocated in dynamic memory (heap). Each element of the array is set to point to a string (to a string literal) stored in static memory. Static memory is neither heap nor stack. Objects in static memory live as long as the program runs. So, formally, there are no problems in your code.
However, it is not a good idea to point to string literals with char *
pointers. String literals are non-modifiable, so const char *
pointers would be much more appropriate in this case.
You can look at each of the individual pieces of new char*[2]
to understand what it does:
new dynamically allocate
new [ ] an array
new [2] of two
new char*[2] pointers to "char" objects
So, it dynamically allocates an array of two pointers to char
s. It returns a pointer to the initial element of the allocated array (this is what the array form of new
always returns). That pointer is stored in charList
. charList
is on the stack (it has automatic storage duration) and points to the dynamically allocated array, which is on the heap.
The two pointers in the dynamically allocated array, charList[0]
and charList[1]
, are set to point to the string literals, "abcde"
and "fghij"
, respectively. The string literals have static storage duration, so they exist for the entire time your program is running.
精彩评论