Programming in C: Unit III (b): Pointers

Null Pointers

with Example C Programs

We have seen that a pointer variable is a pointer to some other variable of the same data type. However, in some cases we may prefer to have null pointer which is a special pointer that does not point to any value.

NULL POINTERS

We have seen that a pointer variable is a pointer to some other variable of the same data type. However, in some cases we may prefer to have null pointer which is a special pointer that does not point to any value. This means that a null pointer does not point to any valid memory address. To declare a null pointer you may use the predefined constant NULL, which is defined in several standard header files including <stdio.h>, <stdlib.h>, and <string.h>. After including any of these files in your program, write

int *ptr = NULL;

You can always check whether a given pointer variable stores address of some variable or contains a NULL by writing:

if (ptr = = NULL)

{

Statement block;

}

You may also initialize a pointer as a null pointer by using a constant 0, as shown below.

int ptr;

ptr = 0;

Programming Tip: It is a logical error to dereference a null pointer.

This is a valid statement in C, as NULL which is a preprocessor macro typically has the value, or replacement text, o. However, to avoid ambiguity it is always better to use NULL to declare a null pointer.

A function that returns pointer values can return a null pointer when it is unable to perform its task.

Null pointers are used in situations where one of the pointers in the program points to different locations at different times. In such situations it is always better to set it to a null pointer when it doesn't point anywhere valid, and to test to see if it's a null pointer before using it.

Note

A run time error is generated if you try to dereference a null pointer.

Programming in C: Unit III (b): Pointers : Tag: : with Example C Programs - Null Pointers