When you take the address of the variable a
by writing &a
, what you're really doing is generating a pointer to a
.
%p
is designed for printing pointers. You should use %p
to print pointers.
%d
is not designed for printing pointers. It tries to print their values as signed decimal, which can be confusing (as you've seen), and it may not print the entire value, on a machine where pointers are bigger than integers. (For example, if you try to print pointers with %d in most "64 bit" environments, you can get even stranger results -- and that might be part of what happened here.)
This is an easy mistake to make. Good compilers should warn you about it. Mine says "warning: format specifies type 'int' but the argument has type 'int *'".
But yes, both 0x7ffd8585280c
and -2054871028
do "point to the same address in RAM", because they're both the same number, the same address. (Well, they're trying to be the same address. See footnote below.)
I'm not sure what you mean by "And how can I get the value". Are you trying to get the value of the pointer, or the value of what the pointer points to?
You've already got the value of the pointer -- it's the address 0x7ffd8585280c
. And since we know it points to the variable a
, we know the value it points to, too. Things will be a bit more clear if we do it like this:
int a = 5;
int *ip = &a;
printf("value of pointer: %p\n", ip);
printf("pointed-to value: %d\n", *ip);
Without the explicit pointer variable ip
, we could write
int a = 5;
printf("value of pointer: %p\n", &a);
printf("pointed-to value: %d\n", *&a);
But that's pretty silly, because the last line is equivalent to the much more straightforward
printf("pointed-to value: %d\n", a);
(Taking the address of a variable with &
and then grabbing the contents of the pointer using *
is a no-op: it's a lot like like writing a + 1 - 1
.)
Footnote: I said that 0x7ffd8585280c
and -2054871028
were the same number, but they're not, they're just trying to be. 0x7ffd8585280c
is really -140748133160948
, and -2054871028
is really 0x8585280c
, which is the lower-order 8 digits of 0x7ffd8585280c
. It looks like %p
on your machine is printing pointers as 48-bit values by default. I was about to be surprised by that, but then I realized my Mac does the same thing. Somehow I'd never noticed that.