Home »
C++ programs
C++ program to declare an integer variable dynamically and print its memory address
In this C++ program, we are going to learn how to declare an integer variable at run time (dynamically)? Here, we are declaring variable dynamically and printing its address.
Submitted by IncludeHelp, on May 04, 2018
Here, we will learn how we can declare an integer variable dynamically and how to print address of declared memory block?
In C++ programming, we can declare memory at run time for any type variable like char, int, float, integer array etc. To declare memory at run time (dynamically), we use new operator. I would recommend reading about new operator first.
Consider the following program:
#include <iostream>
using namespace std;
int main()
{
//integer pointer declartion
//It will contain the address of dynamically created
//memory blocks for an integer variable
int *ptr;
//new will create memory blocks at run time
//for an integer variable
ptr=new int;
cout<<"Address of ptr: "<<(&ptr)<<endl;
cout<<"Address that ptr contains: "<<ptr<<endl;
//again assigning it run time
ptr=new int;
cout<<"Address of ptr: "<<(&ptr)<<endl;
cout<<"Address that ptr contains: "<<ptr<<endl;
//deallocating...
delete (ptr);
return 0;
}
Output
Address of ptr: 0x7ffebe87bb98
Address that ptr contains: 0x2b31e4097c20
Address of ptr: 0x7ffebe87bb98
Address that ptr contains: 0x2b31e4098c50
Here we are declaring an integer pointer ptr and printing the address of ptr by using &ptr along with stored dynamically allocated memory block.
After that we are declaring memory for integer again and printing the same.
From this example - we can understand memory blocks are allocating dynamically, each time different memory blocks are storing in the pointer ptr.