Let us learn about Null pointer in C programming and understand its implementation with an example, explanation, advantages, disadvantages and much more.
A pointer is a variable which is used to store the address of another variable which is of the same data type.
However, there are some scenarios where we may require a pointer that does not point to any variable in the memory.
What is a Null Pointer?
The Null pointer is a special pointer that does not point to any valid memory address. The Null pointer is, therefore, assigned to constant NULL. The null pointer points to the base address of the data segment.
In other words, a null pointer refers to a pointer variable that does not point to a valid address. The NULL is an identifier and not a keyword.
How To Declare A Null Pointer?
A Null pointer can be declared using the constant NULL which is defined in several standard header files enlisted below:
You might have to include any of these header files in your C program. Since NULL is a macro, you have to define it before its declaration in your source code.
There are three ways to declare a null pointer in C programming language. Let us see both these ways.
- Include the standard library header files and initialize a pointer with a constant NULL.
int *ptr = NULL:
- Initialize the pointer variable with a Zero.
int *ptr = 0;
- You can also use (void *)0 as a null pointer constant, but using NULL is cleaner because it makes the purpose of the constant more evident and helps to avoid ambiguity.
Note: A run-time error is generated if you try to dereference a Null pointer.
Where Do We Use NULL Pointers?
The Null pointers are used in situations where one of the pointers in the program points to different locations at different times.
In such situations, it is always better to set it to a null pointer when it doesn’t point to any valid memory location and to test to see if it’s a null pointer before using it.
Note: This example of null pointer in C programming is compiled with GNU GCC compiler using CodeLite IDE on Microsoft Windows 10 operating system.
C Program To Implement NULL Pointers
int *ptr_f = NULL;
int *ptr_s = 0;
printf("\nFirst Pointer:\t%p\n", ptr_f);
printf("\nSecond Pointer:\t%p\n", ptr_s);
Note: We’re using %p as the format specifier to print the value of the Null pointer “ptr”.
- The NULL pointer has its own type std::nullptr_t.
- The Null pointers are used to create linked lists.
- It is implicitly comparable and convertible to any pointer type or pointer-to-member type.
- It helps to avoid crashing a program abnormally.
- A function that returns pointer values can return a null pointer when it is unable to perform a task.
- It is not implicitly comparable and convertible to integral types, except for bool.
If you have any doubts about Null pointer in C programming, let us know about it in the comment section.
|MORE ON POINTERS|