Reputation: 302
int *p = NULL ,c , *q;
c=10;
p = &c;
q = p;
printf ("%d and %d ",&p, &q );
Output:
2686788 and 2686780
My question is: As far I assume, I thought the memory address will be same, as I have assigned p
into q
. May be I am wrong.
Upvotes: 3
Views: 140
Reputation: 106012
p
and q
are two different variables and their addresses are different. &p
and &q
are addresses of p
and q
respectively.
The content of p
and q
will be the same, i.e. they will contain the same memory address after the assignment
q = p;
p
and q
both are pointing to the same memory location now. As for the illustration this is shown in the below ASCII art:
p
+-------+
| | c
0x200 | 0x100 +---------+ +-------+
| | +-> | |
+-------+ | 10 |
q +-> | |
+-------+ | +-------+
| | | 0x100
0x300 | 0x100 +---------+
| |
+-------+
p = q but &p != &q
NOTE: To print the pointer data type use %p
specifier in printf
.
printf ("%p and %p ", (void *)&p, (void *)&q );
Upvotes: 15
Reputation: 223719
You're confusing the content of variables with their address. In this case the content of both p and q is the address of c. However, being distinct variables their addresses will always be different.
Upvotes: 2
Reputation: 20889
You are printing the address of the pointers themselves, not the pointer values:
// Prints the memory location of the pointers
printf ("%d and %d\n", &p, &q);
// Prints the values of the pointers
printf ("%d and %d\n", p, q);
// Prints the values that the pointers point to
printf ("%d and %d\n", *p, *q);
Upvotes: 1
Reputation: 5322
You are showing the address of the variable, not the address it's pointing to.
Both p and q are pointing to the same address, but are different variables, this way they've different addresses.
i.e:
c(address: 1000) -> 10
p(address: 1010) -> 1000
q(address: 2020) -> 1000
change to this, and you should see the value you want.
int *p = NULL ,c , *q;
c=10;
p = &c;
q = p;
printf ("%p and %p ",p, q );
%p prints the address the pointer is pointing to.
Upvotes: 1