
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why is address zero used for the null pointer in C/C++?
In C/C++, a null pointer is a special pointer that does not point to any valid memory location. Address 0 is used for Null Pointers because address 0 is reserved by the system, and it is guaranteed not to be used for valid data.
So, when a pointer is assigned the value 0 (or nullptr), it means the pointer points to nothing.
Some uses of null pointers are:
- To initialize a pointer variable when that pointer variable isn't assigned any valid memory address yet.
- To pass a null pointer to a function argument when we don't want to pass any valid memory address.
- To check for null pointer before accessing any pointer variable. So that, we can perform error handling in pointer related code e.g. dereference pointer variable only if it's not NULL.
In C++ if we assign 0 in any pointer that means the pointer pointing to the NULL.
Initializing a Pointer with Zero
The address zero is reserved to represent a null pointer, and the following syntax shows how to initialize a pointer with a null (zero) address:
Float *p = 0 //initializing the pointer as NULL.
Algorithm
The following is the algorithm to Address Zero is used for Null Pointer in C/C++.
Begin. Declare a pointer p of the integer datatype. Initialize *p= NULL. Print "The value of pointer is". Print the value of the pointer p. End.
Example
In this example, we create a null pointer and prints its value, which generates the output as 0 or nullptr.
#include <stdio.h> int main() { int *p= NULL;//initialize the pointer as null. printf("The value of pointer is %p\n", (void*)p); return 0; }
Following is the output to the above program
The value of pointer is (nil)
#include<iostream> using namespace std; int main() { int* p = NULL; // Initialize the pointer as null cout<<"The value of pointer is "<<p<<endl; return 0; }
Following is the output to the above program
The value of pointer is 0.