NULL Pointer in C++ language

NULL pointer is a type of pointer of any data type and generally takes a value as zero. This is however, not mandatory. This denotes that NULL pointer does not point to any valid memory address.
For Example
int *ptr;
ptr = 0;
The above statement denotes ptr as an integer pointer type that does not point to a valid memory address. This shows that ptr has a NULL  pointer value.


The difference between void pointer and NULL pointers:

A void pointer is a special type of pointer of void type and denotes that it can point to any data type. NULL pointers can take any pointer type, but do not point to any valid reference or memory address. It is important to note that a NULL pointer is different from a pointer that is not initialized.  

Write a C++ program which demonstrate the use of NULL pointer.

#include<iostream>
using namespace std;
int *ptr = NULL;
int main()
{
*ptr  = 500;
cout<<"Value of ptr is : "<<*ptr;
return 0;
}

The above program output is tested on www.jdoodle.com

Output:
Segmentation fault (core dumped)

2. Write a C++ program which demonstrate the use of NULL pointer.


#include<iostream>
using namespace std;
int *ptr = NULL;
int main()
{
int x=10;
ptr  = &x;
cout<<"Value of ptr is : "<<*ptr;
*ptr = 20;
cout<<"Value of ptr is : "<<*ptr;
return 0;
}

The above program output is tested on www.jdoodle.com

Output:
Value of ptr is : 10
Value of ptr is : 20


Thanks
Mukesh Rajput
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: