Why does a C-Array have a wrong sizeof() value when it's passed to a function? [duplicate] Why does a C-Array have a wrong sizeof() value when it's passed to a function? [duplicate] arrays arrays

Why does a C-Array have a wrong sizeof() value when it's passed to a function? [duplicate]


When you pass an array into a function in C, the array decays into a pointer to its first element. When you use sizeof on the parameter, you are taking the size of the pointer, not the array itself.

If you need the function to know the size of the array, you should pass it as a separate parameter:

void test(int arr[], size_t elems) {   /* ... */}int main(int argc, const char * argv[]) {   int point[3] = {50, 30, 12};   /* ... */   test(point, sizeof(point)/sizeof(point[0]));   /* ... */}

Also note that, for a similar reason (taking the sizeof a pointer), the sizeof(point)/sizeof(point[0]) trick doesn't work for a dynamically allocated array, only an array allocated on the stack.


Because array is decayed to a pointer when passed as function argument, so sizeof gives you 4 and 8 for 32- and 64-bit platforms respectively.


Also, it's important to understand that sizeof is evaluated at compile time. Since that's the case, it doesn't make sense to expect different output in test() depending on what was passed in. The sizeof calculation was done when the function was compiled.