Home >Backend Development >C++ >How to Determine the Size of an Array Passed as a Function Argument in C ?
Array Size Determination in C Function Parameters
Unlike in the main function, determining the size of an array passed as an argument to a function in C using sizeof() requires a reference template. This is because arrays decay to pointers when passed to functions.
Array Decay to Pointers
Consider the following code snippet:
int length_of_array(int some_list[]);
Despite the declaration with square brackets, some_list decays to an integer pointer int* when passed as an argument. As a result, sizeof(some_list) returns the size of a pointer, not the array size.
Reference Template Solution
To determine the size of an array correctly, use a reference template. For example:
template<size_t n> int length_of_array(int (&arr)[N]) { std::cout <p><strong>Exception: Multidimensional Arrays</strong></p> <p>There is one exception to the array decay rule. Multidimensional arrays retain their dimensionality and are not passed as pointers. Hence, sizeof() can be used directly to determine their size:</p> <pre class="brush:php;toolbar:false">int a[3][4]; std::cout
The above is the detailed content of How to Determine the Size of an Array Passed as a Function Argument in C ?. For more information, please follow other related articles on the PHP Chinese website!