This question already has an answer here:
Complete example:
#include <stdio.h>
void test(int arr[]) {
int arrSize = (int)(sizeof(arr) / sizeof(arr[0]));
printf("%d\n", arrSize); // 2 (wrong?!)
}
int main (int argc, const char * argv[]) {
int point[3] = {50, 30, 12};
int arrSize = (int)(sizeof(point) / sizeof(point[0]));
printf("%d\n", arrSize); // 3 (correct :-) )
test(point);
return 0;
}
Before passing it to a function, sizeof gives me the correct value. Doing the exact same thing on the exact same array in the function gives weird results. There's one element missing. Why?
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.Because, when it's passed, only the pointer to array is actually being passed.
Your question is also answered at The C Programming FAQ. Question 6.21.
Because sizeof() does NOT tell you the size of an array in C. It does something completely different.
sizeof C++ reference
Because in C, C++, and Objective-C, functions cannot actually have array parameters. They only can have parameters that look like array parameters, but they aren't. In your example,
the compiler sees "there is a parameter that looks like an array of int", and it replaces that parameter with a "pointer to int". So the function that you wrote is absolutely, one hundred percent, identical to
Therefore, inside the function sizeof (arr) will give you the size of a "pointer to int".
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 intest()
depending on what was passed in. Thesizeof
calculation was done when the function was compiled.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:
Also note that, for a similar reason (taking the
sizeof
a pointer), thesizeof(point)/sizeof(point[0])
trick doesn't work for a dynamically allocated array, only an array allocated on the stack.