Understanding array size while passing it to another function without explicitly specifying its size can be a challenge in C . This question arose from the need to execute a loop within a function receiving an array as an argument.
The initial approach, using a conditional check for a NULL pointer value, proved insufficient due to the potential presence of unexpected values in the array.
An effective solution in C involves leveraging templates and passing the array by reference:
template <typename T, int N> void func(T (&a)[N]) { for (int i = 0; i < N; ++i) a[i] = T(); // reset all elements }
By specifying the array size N as a template parameter, the function knows the exact array size it is working with. This approach ensures the loop iterates over the intended number of elements.
To utilize this template function, an array can be passed as follows:
int x[10]; func(x);
It's important to note that this approach only works for arrays, not pointers. For a more versatile solution, employing a standard library container such as std::vector might be a preferable choice.
The above is the detailed content of How Can I 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!