0

I'm trying to pass an array by reference to funcA.

void funcA(int(&a)[], int k);

int main() {
    int n = 5;
    int x[5];
    funcA(x, n);
    return 0;
}

However when I try to, it throws this error.

 A reference of type "int (&)[]" (non const-qualified) cannot be initialized with a value of type "int [5]"

I tried to find what "non const-qualified" meant, but there weren't any good explanations anywhere. Can someone please explain what it means? Thank you.

anon
  • 73
  • 9
  • means compiler can't convert `int [5]` to `int (&)[]`, but I don't know how to fix this – nobleknight May 01 '21 at 09:53
  • 1
    [here's](https://stackoverflow.com/questions/5724171/passing-an-array-by-reference) some reference for you `on how to pass statically allocated array by reference` – nobleknight May 01 '21 at 10:00
  • 2
    The error message is bogus (using XL or PGI C++ ?). That's because there are no references to an array of unknown size in C++. So `int(&)[]` is an impossibility. Use `int[]`, `int*` or `int(&)[5]`. – rustyx May 01 '21 at 10:01

1 Answers1

1

First of all, you cannot have a reference to an array of unbound size. The closest thing is a reference to a pointer (to the array), i.e. int * (&a). This still gives a problem because a is not constant and the passed parameter x is a constant (the location of the array) - this is actually what the compiler error in the question is referring to. Hence, we need a to be a reference to a constant pointer to a non-constant array, i.e.:

void funcA(int * const (&a), int k)
{
    a[k-1] = 0;  // Just a dummy example
}

int main() {
    int n = 5;
    int x[5];
    funcA(x, n);
    return 0;
}

It should be mentioned that there is no downside to using the more common form of passing an array instead:

void funcA(int *a, int k)
nielsen
  • 5,641
  • 10
  • 27