How to display variable memory address in C++?

- March 17, 2018
As we know, computer memory is a bundle of consecutive memory locations. Each memory location has a unique address that is started from 0 and rises to 1, 2 , 3 and respectively.
Computer program occupies a certain range of memory locations, at the time of execution. In the same way, each variables and functions defined in the program also occupies certain memory locations. Suppose, an integer type variable named "x" is equal to 920, occupies a memory address "1011", then the properties of this variable can be shown as below:
Displayed memory address of variable

In the above pictorial form, box represents the memory location allocated for the variable 'x'. We can easily access the value of this variable with the reference of its name (such as "cout<<x;").

Displaying Memory Address

We can easily display memory address of any variable with the help of address operator "&" that is used before the variable name. For example, to display memory address of variable 'x' the statement is:
cout<<&x;
After execution of the above piece of code, the address of memory will be displayed in hexadecimal format such as 0x6fsttt98. The address of a variable is not specified. The memory address will be randomly selected by the operating system at program runtime. Different available memory location is assigned to the variable when each time the program is executed.

Example Program to Show Memory Address

The following C++ program inputs a number from user and displays it's value and memory address on the screen.
#include<iostream>
using namespace std;
main()
 {
   int num;
   cout<<"Enter any number:";
   cin>>num;
   cout<<"You entered ="<<num\n;
   cout<<"The memory address is ="<<&num\;
   return 0;
 }

Output of Program

Enter any number: 150

You entered = 150
The memory address is = 0x6acff71