Home >Backend Development >C++ >How Do You Determine the Size of an Array Passed to a C Function?
Determining Array Size When Passing to Functions in C
Unlike in the main function, where sizeof() directly returns the size of an array, passing an array to a function requires consideration due to array decay to pointers.
Array Decay to Pointers
When passed as an argument, arrays decay to pointers to their first element. This means that the expression sizeof(some_list) within a function will give the size of the pointer, not the size of the entire array.
Sizeof Ratio Problem
Using the expression (sizeof(some_list)/sizeof(*some_list)) to calculate the array size does not work because:
This ratio always results in 1, regardless of the array size. Thus, the function length_of_array always returns 1.
Alternative Method Using Templates
To accurately determine an array's size when passed to a function, use a template:
template<size_t N> int length_of_array(int (&arr)[N]) { return N; }
This approach uses a template parameter N to specify the array's size, which is then returned by the function.
The above is the detailed content of How Do You Determine the Size of an Array Passed to a C Function?. For more information, please follow other related articles on the PHP Chinese website!