Reputation: 53
int main() {
int *x;
int *y;
y = x;
printf("%p %p", &x,&y); // prints 0061FF1C 0061FF18
printf("%p %p", x, y); // prints 00400080 00400080
return 0;
}
Why don't these print the same thing? I thought using just the x and the &x would get to the same value. Also, why are the bottom ones matching if the top one's arent?
Upvotes: 1
Views: 118
Reputation: 7198
With int *x;
you set x
as a pointer. Its value is the address of the pointed value.
So:
*x
= the integer value
x
= the pointer, i.e., the address of the value, address stored at x
&x
= the address of the pointer. This is the address of the address.
Then y=x;
copies the uninitialized address, not the value.
Upvotes: 1
Reputation: 47923
Suppose you wrote this:
int main() {
int x = 5;
int y;
y = x;
printf("%p %p", &x, &y);
printf("%d %d", x, y);
}
Would you expect both lines to print the same?
Upvotes: 1
Reputation: 211560
When you say y = x
in this case it just means that y
assumes whatever pointer value x
happened to have. You never initialized x
with a value, so it's just some random junk.
The address of x
and y
themselves is going to be different. These are two separate variables representing two separate pointers. You can assign their value to be the same, but their address remains distinct.
You're probably confusing this behaviour with:
int x = 5;
int* y = &x;
Where now y == &x
but &x
and &y
continue to remain distinct.
As C does not have references, you really don't have situations where two independent variables are ever the same address.
Upvotes: 3