Search code examples
c++c++11dynamic-memory-allocationstatic-memory-allocation

Static and dynamic allocation memory addressing?


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?


Solution

  • 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.