1

Possible Duplicate:
What is useful about a reference-to-array parameter?
How do I use arrays in C++?

I am trying to pass the arrays by reference. The problem is I am getting errors for passing these arrays.

error C2664: 'InitializeArrays' : cannot convert parameter 1 from 'int [64]' to 'int (&)[]'

Here is the code:

void InitializeS(int (&s)[], int (&BeforeDecimal1)[]);

int main()
{
   int BeforeDecimal[128],s[128];

   InitializeS(s,BeforeDecimal);

   return 0;
}

void InitializeS(int (&s)[], int (&BeforeDecimal1)[])
{
    for(int i=0;i<128;i++)
    {
        s[i]=0;
        BeforeDecimal1[i]=0;
    }
}

What am I doing wrong?

Community
  • 1
  • 1
Alfred
  • 1,543
  • 7
  • 33
  • 45

3 Answers3

4

In C++ there is unlike as in C no concept of compatible types and the type T[] is unrelated to T[N]. You need to make the reference have a size and the size must equal the one of the array you pass.

C++ also bans references to arrays without bounds as function parameter types (perhaps for this reason).

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
3

Why yours doesn't work

The "array" function argument syntax void foo(int array[]) is misleading in that it has nothing to do with arrays. It is syntactic "sugar" (read: horribly legacy confusion that we're stuck with) for void foo(int* array).

As such, void foo(int (&array)[]) doesn't do what you think it does. It's not even equivalent to void foo(int*& array). In fact, the syntax simply doesn't exist.


Passing arrays by reference

Real arrays have dimensions and these dimensions are part of the static type (and everywhere that you see int[] as a "type" is either using it as an incomplete type, or is merely syntactic sugar for something else), so you will need to state the dimension with the type:

void foo(int (&array)[5])

or use templates:

template <size_t N>
void foo(int (&array)[N])

What if I can't do that?

If you don't know the dimension at compile-time then you are SOL and will have to use a std::vector instead.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

As FredOverflow suggests, you need to use templates to implement this functionality.

Here is a way to implement it:

template<int S1, int S2> void InitializeS(int(&)[S1], int(&)[S2]);

int main()
{
   int BeforeDecimal[100],s[50];

   InitializeS(s,BeforeDecimal);

   return 0;
}

template<int S1, int S2> void InitializeS(int (&s)[S1], int (&BeforeDecimal1)[S2])
{
    for(int i=0;i<128;i++)
    {
        s[i]=0;
        BeforeDecimal1[i]=0;
    }
}

Note that this only works if the size of the arrays is known at compile-time.

Tom Knapen
  • 2,277
  • 16
  • 31