Quick question about pointers

 Filip Petrovic · August 8, 2015 Lets say we have a program like this:``#include 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.

Replies

 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 main(){    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);}````Output:*p = 7p = 2686744After *p = &a;*p = 2686744p = 2686744a = 2686744`` c student · August 9, 2015 p and &p should be different each run no matter how many printfs you use. 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. c student · August 9, 2015 they give different valueshttp://ideone.com/MYnkZq
• 1

C

129,699 followers