Why Array Size Calculation Differs Inside a Function in C
When passing an array to a function, C automatically decays the array into a pointer to its first element. This pointer carries the address of the first array element but not its size.
Consider this example:
#include <stdio.h> void test(int arr[]) { int arrSize = (int)(sizeof(arr) / sizeof(arr[0])); // Incorrect printf("%d\n", arrSize); } int main() { int point[3] = {50, 30, 12}; int arrSize = (int)(sizeof(point) / sizeof(point[0])); // Correct printf("%d\n", arrSize); // Prints 3 test(point); return 0; }
In main, sizeof(point) correctly gives the size of the entire array (12 bytes). However, within test, sizeof(arr) yields 4 bytes (the size of an integer pointer), resulting in an incorrect array size calculation (missing one element).
To resolve this, the array size must be explicitly passed as a separate parameter:
void test(int arr[], size_t elems) { int arrSize = elems; /* ... */ } int main() { int point[3] = {50, 30, 12}; /* ... */ test(point, sizeof(point) / sizeof(point[0])); /* ... */ }
Note that sizeof(point)/sizeof(point[0]) works for stack-allocated arrays but not for dynamically allocated arrays since it relies on the underlying decay mechanism.
The above is the detailed content of Why Does `sizeof` Give Different Array Sizes Inside and Outside a C Function?. For more information, please follow other related articles on the PHP Chinese website!