Home > Backend Development > C++ > How Can I Reliably Determine the Size of an Array Passed to a C Function?

How Can I Reliably Determine the Size of an Array Passed to a C Function?

Susan Sarandon
Release: 2024-12-30 02:53:28
Original
799 people have browsed it

How Can I Reliably Determine the Size of an Array Passed to a C   Function?

Determining Array Size in a Passed Function

The problem arises in C , where determining the size of an array passed to a function poses a challenge due to the inability of sizeof to accurately capture the array's length.

One popular solution suggests terminating the loop when the array element array[i] reaches NULL. However, this approach can lead to errors, as array[i] sometimes contains random garbage values near the end of the array.

Template-Based Solution with Array References

C offers a more reliable solution through templates and array references:

template <typename T, int N>
void func(T (&a)[N]) {
    for (int i = 0; i < N; ++i) a[i] = T(); // reset all elements
}
Copy after login

This template-based function takes an array a of type T with a fixed size of N. By using the reference operator &, it binds the original array to a, allowing for access to the array's elements without passing the size explicitly.

To use this function, simply declare an array and pass it by reference:

int x[10];
func(x);
Copy after login

It's important to note that this solution applies only to arrays, not pointers. For pointer-based arrays, a better option is to use the Standard Template Library (STL) container std::vector, which provides size and element access capabilities.

The above is the detailed content of How Can I Reliably Determine the Size of an Array Passed to a C Function?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template