Null Pointers in C

A null pointer is what results when you convert a null pointer constant to a pointer type. A null pointer constant is an integer constant expression with the value 0, or such an expression cast as the type void *. The macro NULL is defined in stdlib.h, stdio.h and other header files as a null pointer constant.
A null pointer is always unequal to any valid pointer to an object or function. For this reason, functions that return a pointer type usually use a null pointer to indicate a failure condition. One example is the standard function fopen( ), which returns a null pointer if it fails to open a file in the specified mode:


#include <stdio.h>
int main()
	FILE *fp = fopen( "myfile.txt", "r" );
	if ( fp == NULL )
	  // Error: unable to open the file myfile.txt for reading.
	return 0;

Null pointers are implicitly converted to other pointer types as necessary for assignment operations, or for comparisons using == or !=. Hence no cast operator is necessary in the previous example.


You may also like...