Home > Software design >  C Multiple Indirection
C Multiple Indirection

Time:10-27

I am currently watching course about pointers in C and I have a question about multiple indirection. I understood what multiple indirection is and that is ok, but I ran on piece of code and I tried to do the same thing on a little different way and it is not working, and I wounder why? My question is about pointer casting on line 32, why this doesn't work when I cast it like: printf("Value pointed to by gp is:%s\n",(char *)gp); Here is the code:

#include <stdio.h>

int data[3];
char *words[3];

int main(int argc, char **argv)
{
        void *gp;

        char *word = "rijec";
        printf("%s\n",word);

        for(int i = 0; i < 3;i  )
        {
                data[i] = i;
        }
        words[0] = "zero";
        words[1] = "one";
        words[2] = "two";

        gp = data;
        printf("\nAddress of array data is:%p\n",gp);
        for(int i = 0; i < 3; i  )
        {
                printf("Value pointed to by gp is %d\n",*(int *)gp);
                gp = (int*)gp 1;
        }
        gp=words;
        printf("\nAddress of array of strings words is:%p\n",gp);
        for(int i = 0;i < 3; i  )
        {
                printf("Value pointed to by gp is:%s\n",*(char **)gp);
                gp  = (char **)gp 1;
        }

        return 0;
}

CodePudding user response:

On line 32 gp contains the address where the array words is stored (because the array words decays to pointer during the assignment). The array words consists of 3 pointers. When you cast this to char * you tell the compiler to treat this array as if each of its elements is a char and not a pointer. You need to dereference the pointer to get the actual string.

CodePudding user response:

When you do

gp=words;

words is converted to a pointer to the first element of the array. The first element of the array is a char*. Consequently, words is converted to a char**. So gp will hold a pointer of type char**

That's why this:

printf("Value pointed to by gp is:%s\n",(char *)gp);
                                        ^^^^^^^^
                                        wrong cast

is wrong

and this:

printf("Value pointed to by gp is:%s\n",*(char **)gp);
                                        ^ ^^^^^^^^
                                        |  correct cast
                                        |
                                        correct dereferencing

is correct

  • Related