arrayscpointersimplicit-conversionpointer-to-pointer

Converting to char*** from char* [2][2]


I have the following variable

char* a[2][2] = {{"123", "456"}, {"234", "567"}};

I wanted to refer it using another variable. While the cast works, accessing elements of b gives a segmentation fault. Eg.

char*** b = (char***) a;
printf("%s", b[0][0]); // Segmentation fault
printf("%s", a[0][0]); // "123"

I did notice that address of b and a is same, but different with indices specified. It would be helpful to understand exactly why address b[0][0] is different from a[0][0].


Solution

  • To index char *** you have to have char ** pointers pointing to char * pointers.

    char* a[2][2] has only char* pointers. The char ** pointers have to exist somewhere. You have to allocate memory for char ** pointers.

    #include <stdio.h>
    int main() {
        char* a[2][2] = {{"123", "456"}, {"234", "567"}};
        char **b[2] = {a[0], a[1]};
        char ***c = b;
        printf("%s\n", a[0][0]);
        printf("%s\n", b[0][0]);
        printf("%s\n", c[0][0]);
    }