Quick question about pointers

0 Filip Petrovic · August 8, 2015
Lets say we have a program like this:


main() {

int a = 7;
int *p = &a;
//int *h = &p;

printf("%p", p);
printf("%p", &p)


So 'p' is a pointer to an address of an 'a', the first printf will tell me an address of an 'a' , lets say: 200.

But shouldn't the second printf give me an address of a pointer 'p'? if so, then why is it showing me same value: 200?
And why when i write:    *h = &p    : the same (second) printf shows me different value, lets say 196.

Post a Reply


Oldest  Newest  Rating
0 c student · August 9, 2015
they give different values

0 Filip Petrovic · August 9, 2015
Oh...apparently when there are two printfs they give different values, but if there is only one printf and I run it two times (using 'p'  first time and '&p' second time), printf gives the same value. I guess it is because every time the program is ran, it assigns different address, and it just assigned that particular address first time to 'p' and second time to '&p' (correct me if I am wrong). Thanks.
0 c student · August 9, 2015
p and &p should be different each run no matter how many printfs you use.
0 Jon Z. · August 9, 2015
What happens is that you are assigning the address of a (&a) to the value stored at the address that p points to (*p = &a).
Rather the you want the pointer (p) to point there, not to change its value (*p). (p = &a).

// ptr.c by Jon Z.  jon@jonsprog.com

#include <stdio.h>

    int a = 7;
    int *p;
    p = &a; //without the *

    printf("*p = %d\n", *p);
    printf("p = %d\n", p);

    *p = &a; // with the *
    printf("\nAfter *p = &a;\n");
    printf("*p = %d\n", *p);
    printf("p = %d\n", p);
    printf("a = %d\n", a);


*p = 7
p = 2686744

After *p = &a;
*p = 2686744
p = 2686744
a = 2686744
  • 1



One of the most popular languages of all time.

Bucky Roberts Administrator