Recently, I realized that if I create an array on the stack, then the following values will be equal to it:
the address of the variable itself on the stack
the value of this variable (i.e. the same pointer)
the address of the first element of this array
It turns out that when I create an array of type T and size N, an area of sizeof(T)*N bytes appears on the stack. For the code below, all three addresses will be the same:
#include <bits/stdc++.h>
using namespace std;
int main() {
int automaticArray[5] {1, 2, 3, 4, 5};
cout << "Variable value = " << automaticArray << ", variable adress = " << &automaticArray << ", first element addres = " << &automaticArray[0] << endl;
}
If I do the same with an array in a dynamic memory area, it will not be correct. The address of the variable itself (the one that will be on the stack) will differ from the two remaining values.
This is logical, because I store only the pointer on the stack, and 8 bytes are allocated for it. The array itself is located somewhere on the heap. For the example below, the addresses will not be the same:
#include <bits/stdc++.h>
using namespace std;
int main() {
int* dynamicArray = new int[5] {0};
cout << "Variable value = " << dynamicArray << ", variable adress = " << &dynamicArray << ", first element addres = " << &dynamicArray[0] << endl;
}
How is it possible that when creating an array on the stack (consider an example for ints), the first eight bytes will simultaneously contain a pointer to the array (i.e. a pointer to this variable itself), and the first 2 elements from array?
My guess is that the value of the variable (the address of the first element of the array) is not stored anywhere.
I checked this through GodBolt, but I'm not good at assembly, and I'm not 100% sure that my guess is correct.

dynamicArrayis a real, breathing, living thing. What you're seeing is the difference between the two. In the case of a "real" (double air-quotes) array, there is no other option except to get the same memory address for a "real" (double air-quotes) array, since there's nothing else out there. But in case of a pointer you have different things: the pointer, and what it points to.<bits/stdc++.h>is not standard C++ and should not be used.,using namespace std;is not recommended. And new/delete should hardly every be used in modern C++. Usestd::arrayfor fixed size arrays (that at least behaves like an object),std::vector<int>for dynamically allocated (and resizable) arrays. And if you ever need to allocate memory yourself usestd::make_unique(not new).automaticArrayis an array whiledynamicArrayis a pointer, a pointer to first element of an array, not an array. Arrays can decay to pointers to first element but that doesnt mean that arrays are pointers or vice versa