0

I am passing a fixed size array to a function (the size is defined to a constant in the function's definition). However, I still get the error

No matching function for call to 'begin'

# define arr_size 2
void test(int arr0[2]){
    int arr1[]={1,2,3};
    int arr2[arr_size];
    
    begin(arr0); // does not work -- how can I make this work?
    begin(arr1); // works
    begin(arr2); // works
}

There is a related discussion here, however, the array's size was clearly not constant in that case. I want to avoid using vectors (as suggested there) for efficiency reasons.

Does anyone know what the issues is?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
black
  • 1,151
  • 3
  • 18
  • 46
  • 4
    If you want to avoid `std::vector` and always have a fixed size you could use [`std::array`](https://en.cppreference.com/w/cpp/container/array) (it's just a wrapper around a c-style array) - and can be passed to functions by value without problems (in contrast to c-style arrays wich will decay into pointers like @Vlad from Moscow explained in his answer) – Turtlefight Jun 22 '22 at 17:34

1 Answers1

3

This function declaration

void test(int arr0[2]){

is equivalent to

void test(int *arr0){

because the compiler adjusts parameters having array types to pointers to array element types.

That is the both declarations declare the same one function.

You may even write for example

void test(int arr0[2]);

void test(int *arr0){
    //,,,
}

So you are trying to call the function begin for a pointer

begin(arr0);

You could declare the parameter as a reference to the array type

void test(int ( &arr0 )[2]){

to suppress the implicit conversion from an array to a pointer.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335