This question already has an answer here:
-
Why isn't the size of an array parameter the same as within main?
13 answers
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?
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.
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 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,
void test(int arr[])
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
void test (int* arr)
Therefore, inside the function sizeof (arr) will give you the size of a \"pointer to int\".
Because sizeof() does NOT tell you the size of an array in C. It does something completely different.
sizeof C++ reference