Search code examples
cpointersdouble-pointer

explaination double asterisk returned value from array (in C)


I have an array:

char *p[2][3] = {"abc","defg","gi","jklmno","pqrstuvw","xyz"};

and when i print the following syntax the compiler print strange values, and i didn't understand why:

printf("%c", **p); // Print 'j'
printf("%c", *p[1]); // Print 'v'

Thank you.


Solution

  • The initialization of the array is incorrect. Since you're trying to create a 2 dimensional array, some braces are missing:

    char *p[2][3] = {{"abc","defg","gi"},{"jklmno","pqrstuvw","xyz"}};
    

    The specifier s has to be used to print an array:

    printf("%s", **p); //abc
    printf("%s", *p[1]); //jklmno
    

    You should not use the dereference operator directly. Always use the array subscript operator:

    printf("%s", p[0][0]); //abc
    printf("%s", p[1][0]); //jklmno