C - 'char **' differs in levels of indirectness from 'char (*) [6]'

Can someone please explain to me what happened to the following, and more importantly why?

int main( int argc, char *argv[] ) { char array[] = "array"; char **test; test = &array; *test[0] = 'Z'; printf( "%s\n", array ); return 0; } 

EDIT

My example above was based on a function that was crashing:

 void apple( char **pp ) { *pp = malloc( 123 ); *pp[0] = 'a'; // technically this is correct but in bad form *pp[1] = 'b'; // incorrect but no crash *pp[2] = '\0'; // incorrect and crash } 

As Won Caton pointed out to me, although *pp[0] = 'a'; not broken, it is in poor condition. The correct form is the bracket

 void apple( char **pp ) { *pp = malloc( 123 ); (*pp)[0] = 'a'; // correct (*pp)[1] = 'b'; // correct (*pp)[2] = '\0'; // correct } 

Like another MK poster, the FAQ addresses the difference between arrays and pointers: http://www.lysator.liu.se/c/c-faq/c-2.html

+8
c
source share
3 answers

test = &array

incorrect because the test is of type char** and &array is char(*)[6] and is different from char**

An array is not the same type as char* , although C implicitly converts between an array type and char* in some contexts, but it is not one of them. Basically, the expectation that char* matches the type of the array (for example: char[6] ) is incorrect, and so the expectation that accepting the address of the array will result in a char** error.

+9
source share

This will be the way to do what you are trying to do:

 int main( int argc, char *argv[] ) { char array[] = "array"; char (*test)[6]; test = &array; (*test)[0] = 'Z'; printf( "%s\n", array ); return 0; } 

test is a pointer to an array, and the array is different from a pointer, although C makes it easy to use it in my case.

If you want to avoid specifying an array of a certain size, you can use a different approach:

 int main( int argc, char *argv[] ) { char array[] = "array"; char *test; test = array; // same as test = &array[0]; test[0] = 'Z'; printf( "%s\n", array ); return 0; } 
+3
source share

char **test; is a pointer to a pointer, but if you are going to accept the address of the whole array, then it should be a pointer to the entire array ie char (*test)[6];

+1
source share

All Articles