Home > Article > Backend Development > Why Does `sizeof()` Return Unexpected Results for Array Parameters in C Functions?
Why sizeof() Doesn't Work the Same for Array Parameters in C Functions
In C , arrays decay into pointers when passed to functions, rendering the use of sizeof() unreliable for determining array size. To understand this, let's analyze the following function:
int length_of_array(int some_list[]) { return sizeof(some_list) / sizeof(*some_list); }
Issue with the Array Parameter
The parameter some_list is declared as an array, but the function signature is effectively equivalent to int length_of_array(int* some_list). This is because arrays decay into pointers in function parameters.
Effect on sizeof()
Using sizeof(some_list) in this context calculates the size of the pointer, resulting in a value of 1. Dividing by sizeof(*some_list) (the size of an integer) yields 1.
Example
In the given example, despite the array num_list containing 15 elements, the function length_of_array() consistently returns 1, as seen in the output:
This is the output from direct coding in the int main function: 15 This is the length of the array determined by the length_of_array function: 1
Solution Using Template Functions
To determine array size in functions, one can use template functions and pass the array by reference:
template<size_t N> int length_of_array(int (&arr)[N]) { return N; }
In this case, the template parameter N captures the known size of the array, allowing sizeof() to return the correct value.
The above is the detailed content of Why Does `sizeof()` Return Unexpected Results for Array Parameters in C Functions?. For more information, please follow other related articles on the PHP Chinese website!