Search code examples
cpointersmemorydereference

Problem printing the derefrenced value of a pointer


I'm trying to understand the operations of pointers.

For the following bit of code:

void main () {
    int x = 1;
    int y = 2;
    int z = 3;
    
    int *p = &x;
    int *q = &y;
    int *r = &z;

    //print  with labels the values of x, y, z, p, q, r, *p, *q, *r
    printf("x is: %d\n%y is: %d\nz is: %d\n\n",x,y,z);    
    printf("p is: %d\n%q is: %d\nr is: %d\n\n", p, q, r); 
    printf("*p is: %d\n%**q is: %d\n*r is: %d\n\n", *p, *q, *r); 
}

The result using gcc compiler is:

The expected result for the lines:

is:

x is: 1
y is: 2
z is: 3

p is: 6422288
q is: 6422284
r is: 6422280

*p is: 00000001
*q is: 00000003
*r is: 76036FED

according to my understanding that's not what should come out in the last three rows, they should give the same value as the first reason, is there a reason behind this result or is it correct and I'm missing something?


Solution

  • Three thoughts:

    1. printf("p is: %d\n%q is: %d\nr is: %d\n\n", p, q, r); isn't valid. You need to use %p to print a pointer.

    2. All of your printf statements have too many percent characters in them.

    3. I agree with your main point. Assuming you removed the extra percent characters, you should see that *p is 1, *q is 2, *r is 3.

    https://repl.it/repls/OpenAngelicControlflowgraph#main.c