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 << N << std::endl; // Outputs the correct array size return N; }
Exception: Multidimensional Arrays
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:
int a[3][4]; std::cout << sizeof(a) / sizeof(a[0]); // Output: 4 (number of columns)
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!