Home  >  Article  >  Backend Development  >  How to Pass an std::array of Unknown Size to a Function in C ?

How to Pass an std::array of Unknown Size to a Function in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-10-24 19:04:30941browse

How to Pass an std::array of Unknown Size to a Function in C  ?

Passing a std::array of Unknown Size to a Function

In C , how can you create a function that accepts a std::array of a known type, but an unknown size?

Consider the following example:

<code class="cpp">void mulArray(std::array<int, ?>& arr, const int multiplier) {
    for(auto& e : arr) {
        e *= multiplier;
    }
}</code>

Given this function, you can create std::arrays of different sizes and pass them to mulArray:

<code class="cpp">std::array<int, 17> arr1;
std::array<int, 6>  arr2;
std::array<int, 95> arr3;

mulArray(arr1, 3);
mulArray(arr2, 5);
mulArray(arr3, 2);</code>

Is there a simpler way to achieve this, akin to using plain C-style arrays?

No, it is not possible to perform this operation without using function templates or alternative containers like std::vector.

Function Templates Solution

To create a generic function that can handle std::arrays of any size, you need to use a function template:

<code class="cpp">template<std::size_t SIZE>
void mulArray(std::array<int, SIZE>& arr, const int multiplier) {
    for(auto& e : arr) {
        e *= multiplier;
    }
}</code>

This template defines a function that takes an array of integers of any size and multiplies each element by the given multiplier.

A live example of this implementation can be found here: [Live Example](https://godbolt.org/z/Y932XW)

The above is the detailed content of How to Pass an std::array of Unknown Size to a Function in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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