Q:

C++ program to declare an integer variable dynamically and print its memory address

belongs to collection: C++ programs on various topics

0

C++ program to declare an integer variable dynamically and print its memory address

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ programs on various topics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
new and delete operators in C++ with printing valu... >>
<< C++ program to print the size of different types o...