C Programming NULL Pointer



We have already studied the different type of pointer in C. In this tutorial we will be learning about NULL Pointer in C Programming

What is Null Pointer ?

  1. NULL Pointer is a pointer which is pointing to nothing.
  2. NULL pointer points the base address of segment.
  3. In case, if you don’t have address to be assigned to pointer then you can simply use NULL
  4. Pointer which is initialized with NULL value is considered as NULL pointer.
  5. NULL is macro constant defined in following header files –
    • stdio.h
    • alloc.h
    • mem.h
    • stddef.h
    • stdlib.h

Defining NULL Value

#define NULL 0

We have noticed that 0 value is used by macro pre-processor. It is re-commanded that you should not use NULL to assign 0 value to a variable.

#include<stdio.h>

int main(){

int num = NULL;
printf("Value of Number ", ++num);

return 0;
}

Above program will never print 1, so keep in mind that NULL should be used only when you are dealing with pointer.

Re-commanded Articles : Declaring pointers | Initializing pointers

Visual Representation

Below are some of the variable representations of NULL pointer.

float *ptr  = (float *)0;
char  *ptr  = (char *)0;
double *ptr = (double *)0;
char *ptr   = '\0';
int *ptr    = NULL;

you can see that we have assigned the NULL to only pointers.

Example of NULL Pointer

#include <stdio.h>
int main()
{
   int  *ptr = NULL;
   printf("The value of ptr is %u",ptr);

   return 0;
}

Output :

The value of ptr is 0

You can find some of the frequently asked questions about NULL pointer here