In the below program, I have created a *ptr by assigning NULL to it. As far as I know, *ptr=NULL; means, *ptr is pointing to nothing. If this is the case, why ptr and &ptr giving different results?
#include<stdio.h>
int main() {
int *ptr=NULL;
printf("%p \n",ptr);
printf("%p \n",&ptr);
}
output:
0
0x7fff3415dc40
A pointer variable is an object that can point to another object. Here int *ptr = NULL;
declares ptr
as a pointer object, that potentially points to an object of int
.
The value initially stored into this pointer object is NULL
(it is initialized to NULL
, so ptr
does not point to any object).
Now, ptr
too resides in memory. It needs enough bytes to contain the address of the pointed-to object. So it too needs to have an address. Therefore
ptr
evaluates to the address of object that ptr
points to.&ptr
evaluates to the location of the ptr
object itself in memory*ptr
evaluates to the value of the object that ptr
points to, if it points to an object. If it does not point to an object, then the behaviour is undefined.Also, %p
needs a void *
as the corresponding argument, therefore the proper way to print them is
printf("%p\n", (void *)ptr);
printf("%p\n", (void *)&ptr);
ptr
holds the value NULL
which is what you assigned.
&ptr
is the address to the variable ptr
which in your case is 0x7fff3415dc40
A pointer is an address. Such address needs memory space to be stored. So a pointer is stored at a specific address. So &ptr is where the pointer is stored, ptr is the value it points at. So your pointer address is 0x7ff..., and its value is null, iow zero.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With