0

Here is some code:

int static_array[10];
cout<<"sizeof(static_array): " <<sizeof(static_array)<<endl;

int *ptr = static_array;
cout<<"sizeof(ptr): " <<sizeof(ptr)<<endl;

which outputs:

sizeof(static_array): 40
sizeof(ptr): 8

As far as I understand, in C++ arrays are pointers and the sizeof(ptr) function returns the size of the pointer. What I don't understand, if static_array is a pointer (which has to be, since I assigned it to ptr), why its size is actually 40 bytes (10 integers) instead of 8.

Botond
  • 2,640
  • 6
  • 28
  • 44
  • 5
    C++ arrays are not pointers. This is a common pitfall due to the fact that they decay to a pointer when passed as function arguments. But a static array and a pointer are completely different types. Therefore the difference in the result of the `sizeof` operator. – 101010 Jun 12 '15 at 21:22
  • So when static_array is passed as a function argument to sizeof(), why doesn't it decay to a pointer? – Botond Jun 12 '15 at 21:54
  • Because `sizeof` is not a function it's an operator. – 101010 Jun 12 '15 at 22:19
  • Makes sense. Thank you! – Botond Jun 12 '15 at 22:26

0 Answers0