Getting the address using pointers

Pointers are just like variables. Instead of holding the value, it holds the address of another variable. In this article we will discuss some basics of pointers using examples.

It should be carefully noted that the data type of the pointer variable should be same as that of the another variable, to which it is pointing to. For instance, an integer type pointer can hold the address of an integer variable, a character type pointer can hold the address of character variable.

#include<bits/stdc++.h>
using namespace std;
int main(){
	int n=50;
	int* pn;
	pn = &n;
	cout<<"n = "<<n<<endl;
	cout<<"&n = "<<&n<<endl;
	cout<<"pn = "<<pn<<endl;
	cout<<"*pn = "<<*pn<<endl;
	cout<<"&pn = "<<&pn<<endl;
	return 0;
}

The output is shown below.

output of the above program. pointers
output of the above program. pointers

Following points can be noted from the above example

  • Value of &n and pn is same, i.e. pn stores the address of n.
  • Value of n and *pn is same, i.e. using *(de-referencing operator) gives the value of n.

View more on pointers here.

Leave a Reply