Prashant | Wed, 29 Jul, 2020 | 113
We have already discussed it in C programming pointers here I am writing a simple example in C++ programming language to declare, initialize and access the pointers.
Pointers are the variables (a type of special), which stores the address of another variables.
Pointers can store address of other normal variable as well as store the address of another pointer variable. The pointer which stores the address of another pointer variable is known as double pointer or pointer of pointer.
Let's understand both cases through examples...
In this example, we will declare an integer variable and an integer pointer that will store the address of the integer variable.
#include <iostream>
using namespace std;
int main()
{
int a; //normal integer variable
int *ptr; //integer pointer declaration
//pointer initialization
ptr = &a;
//printing the address of a by using "&a" and
//through pointer variable
cout<<"Address of a: "<<&a<<endl;
cout<<"Address of a: "<<ptr<<endl;
//assigning a value to variable a
//and will print using 'a' and pointer 'ptr'
a = 108;
cout<<"Value of a: "<<a<<endl;
cout<<"Value of a: "<<*ptr<<endl;
//changing the value of a using pointer
*ptr = 251;
cout<<"Value of a: "<<a<<endl;
cout<<"Value of a: "<<*ptr<<endl;
return 0;
}
Output
Address of a: 0x7ffede9ec62c Address of a: 0x7ffede9ec62c Value of a: 108 Value of a: 108 Value of a: 251 Value of a: 251
Here,
In this example, we will declare an integer variable and 1) an integer pointer, 2) a pointer to pointer that will store the address the address of first pointer (integer pointer).
#include <iostream>
using namespace std;
int main()
{
int a; //normal integer variable
int *ptr; //integer pointer declaration
int **dptr; //pointer to pointer declaration
//pointer initialization
ptr = &a;
//pointer to pointer initialization
dptr = &ptr;
//printing the addresses of a using pointer
//and address of pointer using pointer to pointer
a = 108;
cout<<"Address of a: "<<ptr<<endl;
cout<<"Address of ptr: "<<dptr<<endl;
//assigning value to 'a' and will print using
//pointer and pointer to pointer
cout<<"Value of a: "<<*ptr<<endl;
cout<<"Value of a: "<<**dptr<<endl;
return 0;
}
Output
Address of a: 0x7ffc1d6b2574 Address of ptr: 0x7ffc1d6b2578 Value of a: 108 Value of a: 108
Here,
Note: To get the value of ptr, which is actually the address of a, we can use *dptr.
I hope this post will be helpful to understand the concept of pointers in C++. Here, I just wrote simple examples of pointers in C++.