What is null pointer in C?

C Programming Language >   Pointer in C Language >   NULL pointer  

Short Question

872


Answer:

Null pointer is a pointer which is pointing to nothing. Null pointer points to empty location in memory. Value of null pointer is 0. We can make a pointer to point to null as below.

int *p =  NULL;
char *p = NULL;


In C, a null pointer is a special value that represents the absence of a valid memory address. It is commonly denoted by the macro NULL, which expands to an implementation-defined null pointer constant.

A null pointer does not point to any valid memory location. It is used to indicate that a pointer variable does not currently point to an object or has not been assigned a valid memory address yet.

Null pointers are often used in conditional statements to check if a pointer is valid or uninitialized before dereferencing it. Attempting to dereference a null pointer can result in undefined behavior, such as program crashes or accessing invalid memory.

Here's an example illustrating the use of null pointers:


#include <stdio.h>

int main() {
    int* ptr = NULL;  // Assigning a null pointer

    if (ptr == NULL) {
        printf("The pointer is currently null.\n");
    } else {
        printf("The pointer is not null.\n");
    }

    return 0;
}

In the above example, a pointer variable ptr is initialized with a null pointer by assigning the NULL macro. The code then checks if ptr is equal to NULL using an if statement. Since ptr is a null pointer, the message "The pointer is currently null." is printed.


This Particular section is dedicated to Question & Answer only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.