Home > Software design >  Understanding pointer to pointers in c
Understanding pointer to pointers in c

Time:06-27

I have the following code:

#include <stdio.h>
    int main(void)
    {
        int a[10]={10,20,30,40,50,60,70,80,90,100};
        int *p;
        p=a;
        int **d=&p;
        printf("Address stored in p:%d\n",p);
        printf("Pointer p's address:%d\n",d);
        printf("Pointer d's content:%d\n",*d);
        printf("Pointed array content:%d\n",(*d)[9]);
        printf("Unexpected:\n");
        for (int i = 0; i < 10;   i)
        {
            printf("%d\n",d[i]);
        }
        printf("Expected:\n");
        for (int i = 0; i < 10;   i)
        {
            printf("%d\n",(*d)[i]);
        }
    }

I realize that the first loop is an incorrect way to dereference a pointer to pointer. Upon execution though I get the following output:

6487520
10
30
50
70
90
2
6487512
1
7607184

The first iteration shows a[0]'s address but why am I getting the array's content with odd indexes? Is this behavior random(depending on compiler) and pointless in understanding it?

CodePudding user response:

We have no way of knowing why it produced those numbers. The general answer is that reading a value from an unknown pointer is undefined behavior. We have no way of knowing what it might return or even if the value returned will be consistent between runs of the program. The program may even crash or produce weird behavior.

The more practical answer though is that we know that d is on the stack so the values we observe are likely also part of the stack. d is a pointer not an integer so it may have a different size. Since we see every second value, it likely means your pointer is twice as large as the size of an int on your system.

You can test this theory by adding something like this:

for (int i = 0; i < 10;   i) {
    printf("Reading int (%d bytes) %ld bytes from the start of d: %d\n",
        sizeof(int),
        (long) (d   i) - (long) d,
        d[i]
    );
}

When I run it on my system I get:

Reading int (4 bytes) 0 bytes from the start of d: -601183712
Reading int (4 bytes) 8 bytes from the start of d: -601183728
Reading int (4 bytes) 16 bytes from the start of d: 10
Reading int (4 bytes) 24 bytes from the start of d: 30
Reading int (4 bytes) 32 bytes from the start of d: 50
Reading int (4 bytes) 40 bytes from the start of d: 70
Reading int (4 bytes) 48 bytes from the start of d: 90
Reading int (4 bytes) 56 bytes from the start of d: -2024523264
Reading int (4 bytes) 64 bytes from the start of d: 0
Reading int (4 bytes) 72 bytes from the start of d: 2048278707
  • Related