Example of NULL Pointer in C++
The below example demonstrates the dereferencing and assignment of a null pointer to another value.
// C++ program to demonstrate the dereferencing and
// assignment of null pointer to another value.
#include <iostream>
using namespace std;
int main()
{
int* ptr = nullptr;
// Checking if the pointer is null before dereferencing
if (ptr == nullptr) {
cout << "Pointer is currently null." << endl;
}
else {
cout << "Pointer is not null." << endl;
}
// *ptr = 10; (to avoid runtime error)
// Assigning a valid memory address to the pointer
int value = 5;
ptr = &value;
// Checking if the pointer is null after assigning a
// valid address
if (ptr == nullptr) {
cout << "Pointer is currently null." << endl;
}
else {
cout << "Pointer is not null." << endl;
cout << "Value at the memory location pointed to "
"by the pointer: "
<< *ptr << endl;
}
return 0;
}
Output
Pointer is currently null. Pointer is not null. Value at the memory location pointed to by the pointer: 5
Explanation: In the example given above first the pointer is pointing to a null value. First, we check whether the pointer is pointing to a null value or not before dereferencing it to avoid any kind of runtime error. Then we assign the pointer a valid memory address and then check it before dereferencing it. As the pointer is not pointing to a null value, the else part is executed.
NULL Pointer in C++
A NULL Pointer in C++ indicates the absence of a valid memory address in C++. It tells that the pointer is not pointing to any valid memory location In other words, it has the value “NULL” (or ‘nullptr’ since C++11). This is generally done at the time of variable declaration to check whether the pointer points to some valid memory address or not. It is also returned by several inbuilt functions as a failure response.
Trying to dereference a NULL pointer i.e. trying to access the memory it points to leads to some undefined behavior leading to the program crash.
Contact Us