-2

I want to do this

void DoSomething (int arr[])
{
// do something
}

but instead of arr[] it's std::array

void DoSomething (std::array <int> arr) // <--- incorrect way to declare an array
{
// do something
}

Using std::vector instead of std::array works, but I expect a workaround with std::array, since arr[] works just fine.

This works too

const int arrSize;
void DoSomething (std::array <int,arrSize> arr)
{
// do something
}

but again, I expect a way to do this without any extra declarations.

4
  • Show a minimal reproducible example, how you are going to call the function and pass arguments. Commented Nov 7, 2023 at 2:17
  • 1
    void DoSomething (int arr[]) ends up passing a pointer and loses all size info so DoSomething does not know how many elements to operate on. Commented Nov 7, 2023 at 2:18
  • Pass a pointer to the first slot, then also pass the capacity of the array. When passing an array to a function, the capacity property is lost. Commented Nov 7, 2023 at 2:18
  • 1
    std::array is an array of a fixed size that must be specified. Commented Nov 7, 2023 at 2:20

1 Answer 1

3

std::array is a template. If you want to accept a std::array of any size, your function will have to become a template as well, eg:

template <size_t N>
void DoSomething (std::array<int, N> arr)
{
    // do something
}

The compiler can then deduce N for you, based on whatever std::array you pass in.

Sign up to request clarification or add additional context in comments.

1 Comment

Consider passing the array by (const) reference (const) std::array<int,N>& arr to avoid copying the array

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.