Joe S Joe S - 1 day ago 4
C++ Question

Dynamic int pointer address?

I have been confused about displaying the address of a dynamic integer.
When I output ptr and &ptr I receive two different addresses, however I am unsure about which address is correctly pointing to the value of the pointer.

int main()
{

//Setting pointer to null.
int *ptr = NULL;

ptr = new int;

*ptr = 10;

//Displaying value the pointer is pointing to, and the address.
cout << "Value pointing to : " << *ptr << endl;
cout << "Address : " << ptr << endl;

Answer

The statement

ptr = new int;

allocates integer in memory and stores the address of the integer in the pointer variable ptr.

ptr itself is a variable and will have an address associated with it. So ptr is a variable which stores address of another variable. When you do

cout << ptr;

you are printing the address of the variable ptr is pointing to.

In contrast

cout << &ptr;

will print the address of ptr itself not that of the variable it is pointing to.

Comments