[Solved] What are the values of pointers and variables according to this C code?


Here’s some code which shows what’s going on (in excruciating detail):

#include <stdio.h>

int main(void)
{
    int a = 11;
    int b = 20;
    int x = -1;
    int y = -1;
    int *ip1 = &a;
    int *ip2 = &x;
    int **ipp = &ip2;

    printf("Addresses:\n");
    printf("   &a = %p\n", (void *)&a);
    printf("   &b = %p\n", (void *)&b);
    printf("   &x = %p\n", (void *)&x);
    printf("   &y = %p\n", (void *)&y);
    printf(" &ip1 = %p\n", (void *)&ip1);
    printf(" &ip2 = %p\n", (void *)&ip2);
    putchar('\n');
    printf("%3s  %3s  %3s  %3s  %14s  %14s  %14s  %4s  %4s  %5s\n",
           "a", "b", "x", "y", "ip1", "ip2", "ipp", "*ip1", "*ip2", "**ipp");
    printf("%3d  %3d  %3d  %3d  %14p  %14p  %14p  %4d  %4d  %5d\n",
           a, b, x, y, (void *)ip1, (void *)ip2, (void *)ipp, *ip1, *ip2, **ipp);

    *ip2 = *ip1 * 7 + b;
    printf("%3d  %3d  %3d  %3d  %14p  %14p  %14p  %4d  %4d  %5d\n",
           a, b, x, y, (void *)ip1, (void *)ip2, (void *)ipp, *ip1, *ip2, **ipp);

    ip1 = ip2;
    printf("%3d  %3d  %3d  %3d  %14p  %14p  %14p  %4d  %4d  %5d\n",
           a, b, x, y, (void *)ip1, (void *)ip2, (void *)ipp, *ip1, *ip2, **ipp);

    ip2 = &y;
    printf("%3d  %3d  %3d  %3d  %14p  %14p  %14p  %4d  %4d  %5d\n",
           a, b, x, y, (void *)ip1, (void *)ip2, (void *)ipp, *ip1, *ip2, **ipp);

    **ipp = 88;
    printf("%3d  %3d  %3d  %3d  %14p  %14p  %14p  %4d  %4d  %5d\n",
           a, b, x, y, (void *)ip1, (void *)ip2, (void *)ipp, *ip1, *ip2, **ipp);

    *ipp = &b;
    printf("%3d  %3d  %3d  %3d  %14p  %14p  %14p  %4d  %4d  %5d\n",
           a, b, x, y, (void *)ip1, (void *)ip2, (void *)ipp, *ip1, *ip2, **ipp);

    return 0;
}

It simply prints the addresses of all the variables except ipp — it’s address is never used by any expression in the code. It then prints the values of each of the plain integers, each of the pointers, and the various dereferenced pointers.

Sample output

Addresses:
   &a = 0x7fff5bacd4f0
   &b = 0x7fff5bacd4f4
   &x = 0x7fff5bacd4f8
   &y = 0x7fff5bacd4fc
 &ip1 = 0x7fff5bacd500
 &ip2 = 0x7fff5bacd508

  a    b    x    y             ip1             ip2             ipp  *ip1  *ip2  **ipp
 11   20   -1   -1  0x7fff5bacd4f0  0x7fff5bacd4f8  0x7fff5bacd508    11    -1     -1
 11   20   97   -1  0x7fff5bacd4f0  0x7fff5bacd4f8  0x7fff5bacd508    11    97     97
 11   20   97   -1  0x7fff5bacd4f8  0x7fff5bacd4f8  0x7fff5bacd508    97    97     97
 11   20   97   -1  0x7fff5bacd4f8  0x7fff5bacd4fc  0x7fff5bacd508    97    -1     -1
 11   20   97   88  0x7fff5bacd4f8  0x7fff5bacd4fc  0x7fff5bacd508    97    88     88
 11   20   97   88  0x7fff5bacd4f8  0x7fff5bacd4f4  0x7fff5bacd508    97    20     20

Make sure you understand what you see — it isn’t hard to connect the dots when all the data is present like that.

solved What are the values of pointers and variables according to this C code?