C++ Null Pointers with examples
In this tutorial, we will learn about null pointers in C++ and see various uses of null pointers with some examples. I will try to make this tutorial easy to understand. Let’s get started.
Null Pointers in C++
A NULL pointer is a special type of pointer that does not point to any memory location. In other words, we can say that a pointer represents an invalid location. Whenever a value is assigned as NULL to a pointer, then that pointer is considered as a NULL pointer. NULL is itself a special type of pointer. When we initialize a pointer with NULL then that pointer also becomes a NULL pointer.
Example to understand what is a NULL pointer.
#include <iostream> using namespace std; int main(){ int *ptr = NULL; // This is a NULL pointer return 0; }
Let’s see some uses of NULL pointer:
- It is used to initialize a pointer when that pointer isn’t assigned any valid memory address yet. That is it’s a good practice to assign a pointer with null if a not valid address is defined.
- It is also useful in handling errors when using the malloc function. Sometimes malloc returns null when memory is not allocated. In that case, we can use NULL for handling errors.
#include <iostream> using namespace std; int main(){ int *ptr; ptr = (int*)malloc(sizeof(int)); if(ptr == NULL) cout<<"Memory could not be allocated"<<endl; else cout<<"Memory allocated successfully"<<endl; return 0; }
OUTPUT: Memory allocated successfully
It is good practice to initialize a pointer as NULL.
It is a good practice to perform a NULL check before dereferencing any pointer to avoid surprises.
To check pointer is null or not.
#include <iostream> using namespace std; int main() { int a = 5; int *ptr = &a; if(ptr != nullptr) { cout << "It is not NULL Pointer" << endl ; } else { cout << "It is a NULL Pointer" << endl; } return 0; }
OUTPUT:
It is not a NULL POINTER.
Hope you liked this tutorial. Happy Learning !!
Also Read: How to set a pointer to null in C++
Leave a Reply