When I try a test program with just these two lines
char array[256];
char** arrayPointer=&array;
I get the error
cannot convert from char*[256] to char**.
Yet if I do this:
char array[256];
char* temp=array;
char** arrayPointer=&temp;
I get no such complaint.
I figured that it was eclipse acting buggy (which my eclipase is acting funny right now) but when I tried to do a cast of the &array
to char**
for the function I ended up with unusual behavior and my debugger implying that the array isn't being modified as it should.
PS. all of this was written by hand, forgive typos.
In C++, arrays and pointers are not the same thing. Arrays in many cases can implicitly be converted to a pointer, but array types and pointer types are different.
In your case, the variable
char array[256];
has type char[256]
. If you take its address by writing &array
, you get a pointer to an array of 256 char
s, which has type char (*)[256]
. This is not the same a char**
. This is actually a good thing. If you could do the conversion, what would happen if you did this?
char array[256];
char** ptrPtr = &array; // Not legal!
*ptrPtr = new char[256];
In this case, the third line would "reassign" array
to point to a new array of 256 elements. However, array
is not a pointer! This operation is meaningless.
The reason you got a weird debugger error when writing
char array[256];
char** ptrPtr = (char**) &array; // Legal, but Bad Times!
*ptrPtr = new char[256];
is that the cast you've put in results in undefined behavior. You're pretending that a pointer to an array of 256 actual char
objects is really a pointer to a pointer to a char
. This is a meaningless cast, so all bets are off when you do it.
On the other hand, if you explicitly introduce a char*
variable like this:
char array[256];
char* ptr = array;
char** ptrPtr = &ptr;
Then everything is fine. In the second line, you create a pointer (actual type char*
) that points to the first element of array
. In the third line, you create a pointer to that new pointer. If you then write
*ptrPtr = new char[137];
Then nothing bad happens; you've just changed where ptr
was pointing, and didn't destroy array
.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With