Array Size Discrepancy When Passing to Function
The sizeof() operator reports an inaccurate value for an array when passed to a function. Consider the following code snippet:
#include <stdio.h> void test(int arr[]) { int arrSize = (int)(sizeof(arr) / sizeof(arr[0])); printf("%d\n", arrSize); // 2 (incorrect) } int main() { int point[3] = {50, 30, 12}; int arrSize = (int)(sizeof(point) / sizeof(point[0])); printf("%d\n", arrSize); // 3 (correct) test(point); return 0; }
When called from main(), the sizeof() operator accurately reports the size of the array, but within the test() function, it underestimates the size by one element. This disparity arises because when an array is passed to a function in C, it decays to a pointer referencing the array's first element. Consequently, sizeof(arr) calculates the pointer's size rather than the underlying array's size.
To remedy this issue, the size of the array should be explicitly passed as a separate parameter to the function:
void test(int arr[], size_t elems) { // ... } int main() { int point[3] = {50, 30, 12}; // ... test(point, sizeof(point) / sizeof(point[0])); // ... }
Alternatively, for dynamically allocated arrays (not shown here), the standard C library function stdlib.h can be used to accurately obtain the array's size.
The above is the detailed content of Why Does `sizeof` Return an Incorrect Array Size When Passing an Array to a C Function?. For more information, please follow other related articles on the PHP Chinese website!