NULL Pointer in C

A NULL pointer is a pointer that has no value or memory address assigned to it; it is just NULL. None of the variables, functions, or objects can be referenced by a NULL pointer. When we want to show that a pointer variable isn’t yet assigned to a valid memory address, we frequently initialise pointer variables with NULL pointers.

int *ptr = NULL;

Simply put, no memory is allocated to a NULL pointer because it often corresponds to the NULL or 0th memory location.

Defeating a reference to NULL

  • A NULL pointer behaves very similarly to a void pointer when dereferencing. Since a NULL pointer is really a VOID pointer in and of itself, we must typecast it into any data type before dereferencing. Failure to do so causes a compile-time error.

Uninitialized pointer versus NULL pointer

  • Null pointers are distinct from uninitialized pointers since they take up no memory space. In other words, it only points to the zeroth position. An uninitialized pointer, on the other hand, signifies that the pointer resides at a garbage value address. Since the garbage value address still refers to a legitimate memory location, it is not a NULL value. Therefore, NULL pointers are chosen to be on the safe side.

Void pointer versus NULL pointer

  • Due to their similar names, NULL pointers and void pointers may appear to be quite similar; nevertheless, a NULL pointer is a pointer with a NULL value address, and a void pointer is a pointer of void data type. Their respective meanings diverge.

example of a NULL pointer :  

 int *ptr = NULL;

example of a VOID pointer:

    void *ptr;

Benefits of using a NULL pointer

  • A pointer variable can be initialised without having a specific memory location assigned to it.
  • It can be used to determine whether a pointer is genuine or not. Making the pointer NULL, which prevents dereference, allows us to verify that.
  • When comparing two pointers, a NULL pointer is used to determine whether the other pointer is actually pointing to a memory address or not.
  • In the case of C programming, we employ it for error management.
  • When passing a pointer with a valid memory location is not desired, we can give a NULL pointer instead.
Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in