Signup/Sign In

Using Null Pointer Program

NULL is a macro in C, defined in the <stdio.h> header file, and it represent a null pointer constant. Conceptually, when a pointer has that Null value it is not pointing anywhere.

If you declare a pointer in C, and don't assign it a value, it will be assigned a garbage value by the C compiler, and that can lead to errors.

Void pointer is a specific pointer type. void * which is a pointer that points to some data location in storage, which doesn't have any specific type.

Don't confuse the void * pointer with a NULL pointer.

NULL pointer is a value whereas, Void pointer is a type.

Below is a program to define a NULL pointer.

#include<stdio.h>

int main()
{
    printf("\n\n\t\tStudytonight - Best place to learn\n\n\n");
    int *ptr = NULL;    // ptr is a NULL pointer

    printf("\n\n The value of ptr is: %x ", ptr);
    printf("\n\n\t\t\tCoding is Fun !\n\n\n");
    return 0;
}

Program Output:

C program example for Null Pointer


Use Null Pointer to mark end of Pointer Array in C

Now let's see a program in which we will use the NULL pointer in a practical usecase.

We will create an array with string values (char *), and we will keep the last value of the array as NULL. We will also define a search() function to search for name in the array.

Inside the search() function, while searching for a value in the array, we will use NULL pointer to identify the end of the array.

So let's see the code,

#include <stdio.h>
#include <string.h>

// declaring the search function
int search(char *ptr[], char* name);

char *names[] = {
    "John",
    "Peter",
    "Thor",
    "Chris",
    "Tony",
    NULL
};

int main(void)
{
    if(search(names, "Peter") != 1) {
        printf("Peter is in the list. \n");
    }
    
    if(search(names, "Scarlett") == -1)  {
        printf("Scarlett not found. \n");
    }

    return 0;
}

// define the search method
int search(char *ptr[], char*name)
{
    register int i;

    for(i=0; ptr[i]; ++i)
    {
        if(!strcmp(ptr[i], name))  return i;

        return -1;  /* name not found */
    }
}


Peter is in the list.
Scarlett not found.

This is a simple program to give you an idea of how you can use the NULL pointer. But there is so much more that you can do. You can ask the user to input the names for the array. And then the user can also search for names. So you just have to customize the program a little to make it support user input.