C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Code Snippets » C/C++ Code Snippets

C++ - Declare Integer variable dynamically, print the memory addresses

By: Priya Kaushal On 23 DEC 2016

Here, we will learn how we can declare an integer variable dynamically and how to print address of declared memory block?

Consider the following program:

#include <iostream>

using namespace std;

int main()
{
    int a;
	int *ptr;
	ptr=new int;
	
	cout<<(&ptr)<<","<<ptr<<endl;
	
	ptr=new int;
	
	cout<<(&ptr)<<","<<ptr<<endl;
	
	delete (ptr);
	
	return 0;	
}







Sponsored Links



Output

0x7ffdd55ec0c8,0x602010
0x7ffdd55ec0c8,0x602030

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.


COMMENTS