I'm learning C++ and I’ve noticed that the sizeof()
-operator works differently on arrays on the stack and on the heap. For instance:
int onStack[5];
int* onHeap = new int[5];
std::cout << "sizeof(onStack)=" << sizeof(onStack) << std::endl;
std::cout << "sizeof(onHeap)=" << sizeof(onHeap) << std::endl;
generates the output
sizeof(onStack)=20
sizeof(onHeap)=4
However, as far as I can tell, both onStack
and onHeap
are just int
pointers, right? I’m aware that you shouldn’t / can’t really use the sizeof()
-operator to get the size of an array, but just out of curiosity, why does it behave differently, depending on whether the array is on the stack or on the heap?
No, onStack
is a int[5]
wich decays to a pointer. They are not the same, hence the sizeof
difference.
Nothing to do with on stack vs on heap, it's really just type difference.