Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address of NULL pointer

Tags:

c

null

pointers

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 
like image 329
Bahubali Avatar asked Oct 22 '17 07:10

Bahubali


Video Answer


3 Answers

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);
like image 160

ptr holds the value NULL which is what you assigned.

&ptr is the address to the variable ptr which in your case is 0x7fff3415dc40

like image 39
Dror Moyal Avatar answered Nov 03 '22 05:11

Dror Moyal


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.

like image 38
SCO Avatar answered Nov 03 '22 05:11

SCO