![]() |
VOOZH | about |
The Null Pointer is the pointer that does not point to any location but NULL. According to C11 standard:
“An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.”
type pointer_name = NULL;
type pointer_name = 0;
We just have to assign the NULL value. Strictly speaking, NULL expands to an implementation-defined null pointer constant which is defined in many header files such as “stdio.h”, “stddef.h”, “stdlib.h” etc.
Following are some most common uses of the NULL pointer in C:
It is a valid operation in pointer arithmetic to check whether the pointer is NULL. We just have to use isequal to operator ( == ) as shown below:
ptr == NULL;The above equation will be true if the pointer is NULL, otherwise, it will be false.
Pointer does not point to anything
By specifically mentioning the NULL pointer, the C standard gives a mechanism using which a C programmer can check whether a given pointer is legitimate or not.
The malloc() function returns the NULL pointer when the memory allocation is failed. We will use this property to check if the memory allocation is successful.
What’s going to happen if we use the following C code:
On some machines, the above would compile successfully but crash when the program is run. Though that doesn't mean it would show the same behavior across all the machines. As the value of NULL in predefined libraries is 0 and the pointer (that's pointing to NULL) is not pointing to any memory location, this behavior occurs.
We can pass a NULL value for pointers that should not contain any value to the function in C.
NULL Pointer Passed
The following table list the differences between a null pointer and a void pointer in C:
NULL Pointer | Void Pointer |
|---|---|
| A NULL pointer does not point to anything. It is a special reserved value for pointers. | A void pointer points to the memory location that may contain typeless data. |
| Any pointer type can be assigned NULL. | It can only be of type void. |
| All the NULL pointers are equal. | Void pointers can be different. |
| NULL Pointer is a value. | A void pointer is a type. |
| Example: int *ptr = NULL; | Example: void *ptr; |