Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof() on arrays on stack vs. on heap

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?

like image 709
Macklin Avatar asked Dec 05 '25 14:12

Macklin


1 Answers

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.

like image 161
Matthieu Brucher Avatar answered Dec 08 '25 02:12

Matthieu Brucher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!