Reputation: 1
I just got started learning about pointers and was executing some code:
#include <stdio.h>
int main(void){
int num = 12; // initialize num to 12
int *pnum = NULL; // initialize the pointer
pnum = # // stores the address of num in pnum
printf("the address of the number is %p\n", &num); // display the address of the number
printf("the address of the pointer is %p\n", &pnum); // display the address of the pointer
printf("the value of the pointer is %p\n", pnum); // display the value of the pointer
printf("the value the pointer is pointing to is %d\n", *pnum); // display the value the pointer is pointing to
return 0;
}
In this code above, It prints out 0xffffcbec
for the address of the number and value of the pointer, and 0xffffcbe0
for the address of the pointer. I want to know the reason. I feel like this is related to some incorrect inputs of data types.
I use VScode btw.
Upvotes: -1
Views: 73
Reputation: 409442
The value of pnum
is the value of &num
, i.e. the location of the variable num
. Therefore &num
and pnum
will print the same.
To make it easier to understand and visualize, I recommend you draw it all out:
+-------+ +------+ +-----+ | &pnum | ---> | pnum | ---> | num | +-------+ +------+ +-----+
That is:
&pnum
is pointing to pnum
pnum
(which is the same as &num
) is pointing to num
Also, the pointer-to operator &
and the dereference operator *
are each others opposites.
So pnum
is the value of &num
. And *pnum
is the value of num
.
And *&num
is plain num
, as the operators cancel out each other.
Upvotes: 4