Null Pointer in C++
Null Pointers Definition :
Null Pointers in C++ language are is nothing but sort of like a variable which works like a locator/indicator to an address values (hence the name pointer).It helps in reducing the code and returning multiple values from a function.
Syntax Of Pointers In C++:
datatype * var_name;
The * operator creates a pointer variable, which points to a data type (like an int) of the same type.The pointer is given the address of the variable you are working with.
Example :
In the below example, pointer is the address of the variable while *pointer and val print the value of the variable
#include <iostream> using namespace std; int main() { int var1 = 3; int var2 = 24; int var3 = 17; cout << "Address of var1 = "<< &var1 << endl; cout << "Address of var2 = " << &var2 << endl; cout << "Address of var3 = " << &var3 << endl; }
Output :
Address of var1 = 0x7ffc4b75300c Address of var2 = 0x7ffc4b753010 Address of var3 = 0x7ffc4b753014
Uses of Null Pointers :
- To pass references for arguments
- In order to access array items
- Numerous values to be returned
- Allocating memory dynamically
- Data structures can be implemented easily.
- Very easy to access memory address by Pointers.
Null Pointer Arithmetic :
Arithmetic of Pointers is different from integer. The following arithmetic of pointer are :
- Increment/Decrement of Pointer.
- Addition/ subtraction of integer to a Pointer.
Example :
In the below program, pointers are used to print the value of array elements.
#include <iostream> using namespace std; int main() { int var = 5; int *pointVar; pointVar = &var; cout << "var = " << var << endl; cout << "Address of var (&var) = " << &var << endl << endl; cout << "pointVar = " << pointVar << endl; cout << "Content of the address pointed to by pointVar (*pointVar) = " << *pointVar << endl; return 0; }
Output :
var = 5 Address of var (&var) = 0x7fff28c63f7c pointVar = 0x7fff28c63f7c Content of the address pointed to by pointVar (*pointVar) = 5
Advantages of Pointers in C++ :
- Arrays can be easily accessed by pointers.
- Memory locations can be easily accessed by pointers.
- Complex data structures can be easily built by the pointers.
Disadvantages of Pointers in C++ :
- Pointers are hard to understand.
- Pointers are slower than variable in C++.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment