Static and dynamic allocation memory addressing?

208 Views Asked by At

I initialized an array in C++ using both static and dynamic allocation.

// dynamic allocation... len is input by user.
int *data = new int [len];
// print memory address
cout<< &data<<endl;
cout<< &data[0]<<endl;
// static allocation...
int *arr1[10];
// print memory address
cout<< &arr1<<endl;
cout<< &arr1[0]<<endl;

I expected that &data and &data[0] to return the same memory address as they point to the location of the first element of the array. However, I obtained the following results :

0x7fffb9f3dd40

0x24c6010

0x7fffb9f3dcf0

0x7fffb9f3dcf0

This seemed to work as expected for arr1. Please can some one explain this? What am I missing?

4

There are 4 best solutions below

3
On BEST ANSWER

data and arr1 are very different here: data is a pointer to an int array, arr1 is an int* array. As such &data is the address of the pointer to the array, not the address of the first element of the array.

0
On

This line of code

cout<< &data<<endl;

Prints the address of the pointer variable, not it's content obtained with new.

0
On

&data returns the address of the data variable itself. &data[0] returns the address of the first element data points to.

2
On

data is pointing to an address on the heap, but &data is pointing to data and that lives on the stack.