2

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?

Macklin
  • 157
  • 1
  • 9

1 Answers1

3

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.

Matthieu Brucher
  • 19,950
  • 6
  • 30
  • 49
  • Wow, that was quick :D thanks, that makes sense! I just looked up array decaying and found this post: https://stackoverflow.com/questions/1461432/what-is-array-decaying, which further clarifies this concept. – Macklin Mar 03 '19 at 13:32
  • 1
    @Macklin • The `onHeap` pointer is not an example of pointer decay. It is an example of being a pointer to a heap allocated array. In modern C++, probably better to use `std::vector`. – Eljay Mar 03 '19 at 13:41