initialize a pointer to a character pointer and initialize an array of pointer each pointing to a character pointer

Viewed 31

I have a question regarding my code here:

    char a = 'A';
    char b = 'B';
    char c = 'C';
    char *ad = &a;
    char *ab = &b;
    char *ac = &c;
    char* cp[] = {ad, ab, ac}; 
    
    char **d = &(cp[2]);  // okay
    // char **d[0] = &(cp[2]);  //variant 1: error: invalid initializer
   // char **d[] = &(cp[2]);    //variant 2: error: invalid initializer

I am not sure why variant1 and variant2 would leads to error. For the original initialization (i.e. the line with comment okay), there was no error. My understanding is I have initialize a pointer (i.e. d) which is pointing to a pointer that pointing to a character. So this seems fine.

For variant1, I thought (based on my understanding) I am initializing an array of pointers where each of them will point to a pointer that points to a character. So in this case, I only initialize the very first element in that array.

Similarly for variant2, I initialize an empty array of pointers that each would points to a character.

Could someone tells me why there is error of coming from the compiler here?

And is my understanding of variant 1 correct? i.e. d is an array of pointers where each entry in the array would points to a pointer that points to a character?? I thought this is correct. So why is it that I cannot initialize variant 1?

For variant2, I also thought that I have an array of pointers each pointing to a pointer that points to a character.

1 Answers

This compiles cleanly...

char a = 'A';
char b = 'B';
char c = 'C';
char *ad = &a;
char *ab = &b;
char *ac = &c;
char *cp[] = {ad, ab, ac}; // be consistent

char **d    =   &cp[2];
char **e[1] = { &cp[2] }; // cannot dimension an array to have 0 elements
char **f[]  = { &cp[2] }; // compilers count more accurately than people

Note the absence of unnecessary "()".

Array initialisers are listed within enclosing braces. "{}"

Exception to last statement: char foo[] = "bar";... "string" array elements do not require braces unless one gets silly:

char foo[] = { 'b', 'a', 'r', '\0', };
Related