NULL Pointer in C

A NULL pointer is defined as the special pointer value that points to nowhere in the memory. If it is too early in the code to assign a value to the pointer, then it is better to assign NULL (i.e., or 0) to the pointer.

For example:

 

#include<stdio.h>
int *p=NULL;

Here, the pointer variable p is a NULL pointer, this indicates that the pointer variable p does not point to any part of the memory. The value for NULL is defined in the header file “stdio.h”. Instead of using NULL, we can also use ” or 0. The programmer can access the data using the pointer variable p if and only if it does not contain NULL. The error condition can be checked using the following statement:

if(p==NULL)
printf(“p does not point to any memory\n”);
else
{
printf(“Access the value of p\n”);
………………….
}

Note : A pointer variable must be initialized. If it is too early to initialize a pointer variable, then it is better to initialize all pointer variables to NULL in the beginning of the code. This avoids unintentional use of an un-initialized pointer variable.

Example :  Consider the following statements:
int *x;
int y;
x=y;   /* Error*/

Note :  The value of data variable can not be assigned to a pointer variable. So, the statement x=y; result in an error . The correct statement is x=&y;

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s