-2

I'm trying to pass an array to a function but I'm getting this weird error

const int size = 2;
void foo(short (&a)[size]){
  cout << a;
}
void testSequence(short a[size]){
  foo(a);
}

error: invalid initialization of reference of type ‘short int (&)[4]’ from expression of type ‘short int*’

2 Answers2

1

When you declare a function parameter like this

short a[size]

you are declaring a pointer, not an array:

[dcl.fct] After determining the type of each parameter, any parameter of type “array of T” or of function type T is adjusted to be “pointer to T”.

foo(short (&a)[size]) requires a reference to an array of size size. A pointer cannot be converted to one.

n. 'pronouns' m.
  • 95,181
  • 13
  • 111
  • 206
1

The declaration

void testSequence(short a[size]);

is the same as

void testSequence(short a[]);

which is the same as

void testSequence(short* a);

Hence, the call

foo(a); 

from the function is not valid.

In order to be able to use

foo(a);

you'll have to use:

void testSequence(short (&a)[size]){
  foo(a);
}

The line

cout << a;

in foo is not right either. There is no overload of the << operator that allows writing a reference to an array of ints to cout. You can use:

for ( size_t i = 0; i < size; ++i )
{
   std::cout << a[i] << std::endl;
}
R Sahu
  • 196,807
  • 13
  • 136
  • 247