Null Pointer in C

Null Pointer in C

In this article, I am going to discuss Null Pointer in C with Examples. Please read our previous articles, where we discussed Pointer to Constant in C.

Null Pointer in C:

The pointer variable which is initialized with the null value is called the Null Pointer. Null Pointer doesn’t point to any memory location until we are not assigning the address. The size of the Null pointer also is 2 bytes according to DOS Compiler.

Null Pointer in C

The null pointer can be used as an error code of a function. Null can be used as a constant integral value.

Example: int x=NULL; //int x=0;

By using NULL, we can check the status of a resource, i.e. it is busy with any process or free to utilize.

Program:
#include<stdio.h>
void main ()
{
    int a,b;
    int *ptr = (int *) 0;
    if (ptr == 0)
    {
        ptr = &a;
        a = 100;
    }
    if (ptr == (int *) 0)
    {
        ptr = &b;
        b = 200;
    }
    printf ("value of *ptr: %d ", *ptr);
}

Output: value of *ptr: 100

What will be the output in the below program?
#include<stdio.h>
int main ()
{
    int a, b;
    int *ptr = (int *) 0; //int *ptr = NULL;
    if (ptr == (int *) 0)
    {
        ptr = &a;
        a = 10;
        printf ("value of a= %d", *ptr);
        ptr = (int *) 0;
    }
    if (ptr == NULL)
    {
        ptr = &b;
        b = 20;
        printf ("\nvalue of b= %d", *ptr);
    }
    return 0;
}

Output:

Null Pointer in C Programming Language with Examples

What will be the output from the below program?
#include<stdio.h>
int main ()
{
    int a, b;
    int *ptr = (int *) NULL;
    ptr = &a;
    a = 32767;
    b = *ptr;
    printf ("\n %d %d %d", a, b, *ptr);
    *ptr = 0;
    printf ("\n %d %d %d", a, b, *ptr);
    return 0;
}

Output:

Null Pointer in C Language with Examples

What will be the output from the below program?
#include<stdio.h>
void main ()
{
    int a, b;
    unsigned char *ptr = (unsigned char *) 0;
    ptr = &a;
    a = 511;
    b = *ptr;
    printf ("%d %d %d \n", a, b, *ptr);
    *ptr = 10;
    printf ("%d %d %d", a, b, *ptr);
}

Output:

Null Pointer in C with Examples

Note: On integer variable when we are applying unsigned character pointer then it can access and manipulate 1byte data only because indirection operator behavior is datatype dependent.

In the next article, I am going to discuss Void Pointer in C language. Here, in this article, I try to explain Null Pointer in C. I hope you enjoy this Null Pointer in C article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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