2

Possible Duplicate:
Sizeof array passed as parameter

Given the following code, the system I'm currently on (which seems to be 64-bit given the size of a pointer) prints:

32
4

Now, the size of an int should be 4 bytes on this system, so 8*4 = 32 makes sense. Also, I understand that the size of a pointer should also be 4 bytes, which is what I'm guessing is happening to the array in foo.

My question is why is sizeof(arr) in the foo function treated differently than sizeof(myarray) in main() when both are specifically int[8] arrays? I had anticipated receiving 32 in both cases and it confuses me why it would end up otherwise.

#include <iostream>

void foo(int arr[8])
{
    std::cerr << sizeof(arr) << std::endl;
}

int main()
{
    int myarray[8];
    std::cerr << sizeof(myarray) << std::endl
    foo(myarray);
}
Community
  • 1
  • 1
John Humphreys
  • 37,047
  • 37
  • 155
  • 255

2 Answers2

2

Arrays decay into pointers when passed into functions such that you are printing the sizeof the array pointer of int of 4 bytes in foo().

The sizeof(myarray) prints the size of the array which is 32 (num elements x size of int).

0

Its because arrays that are function arguments get translated to pointers. so

void foo(int arr[8])

is actually

void foo(int *arr)
Daniel
  • 30,896
  • 18
  • 85
  • 139