NULL pointer in C
At the very high level, we can think of NULL as a null pointer which is used in C for various purposes. Some of the most common use cases for NULL are
- To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address yet.
* pInt = NULL;chevron_right
- To check for a null pointer before accessing any pointer variable. By doing so, we can perform error handling in pointer related code e.g. dereference pointer variable only if it’s not NULL.
(pInt != NULL)
/*We could use if(pInt) as well*/
- To pass a null pointer to a function argument when we don’t want to pass any valid memory address.
/*Fun specific stuff is done with ptr here*/
Pointer to a Null Pointer
As Null pointer always points to null, one would think that Pointer to a Null Pointer is invalid and won’t be compiled by the compiler. But it is not the case.
Consider the following example:
Not only this program compiles but executes successfully to give the output as
Pointer to a null pointer is valid
What happens here is that when a Null pointer is created, it points to null, without any doubt. But the variable of Null pointer takes some memory. Hence when a pointer to a null pointer is created, it points to an actual memory space, which in turn points to null.
Hence Pointer to a null pointer is not only valid but important concept.
- NULL pointer in C
- Double Pointer (Pointer to Pointer) in C
- 'this' pointer in C++
- Opaque Pointer
- A C/C++ Pointer Puzzle
- void pointer in C / C++
- Pointer to an Array | Array Pointer
- Function Pointer in C
- Type of 'this' pointer in C++
- Pointer vs Array in C
- Passing Reference to a Pointer in C++
- Sum of array using pointer arithmetic
- C | Advanced Pointer | Question 1
- Difference between pointer and array in C?
- C | Pointer Basics | Question 4