2

It seems like g++ ignores difference in array sizes when passing arrays as arguments. I.e., the following compiles with no warnings even with -Wall.

void getarray(int a[500])
{
    a[0] = 1;
}

int main()
{
    int aaa[100];
    getarray(aaa);
}

Now, I understand the underlying model of passing a pointer and obviously I could just define the function as getarray(int *a). I expected, however, that gcc will at least issue a warning when I specified the array sizes explicitly.

Is there any way around this limitation? (I guest boost::array is one solution but I have so much old code using c-style array which got promoted to C++...)

nimrodm
  • 23,081
  • 7
  • 58
  • 59
  • Duplicate of: http://stackoverflow.com/questions/1328223/sizeof-array-passed-as-parameter – Richard Corden Sep 03 '09 at 09:35
  • @Richard: the answer to that question contains the clue to this one. The question however is different. This one is about type preservation. – xtofl Sep 03 '09 at 09:48

2 Answers2

10

Arrays are passed as a pointer to their first argument. If the size is important, you must declare the function as void getarray(int (&a)[500]);

The C idiom is to pass the size of the array like this: void getarray(int a[], int size);
The C++ idiom is to use std::vector (or std::tr1::array more recently).

rpg
  • 7,746
  • 3
  • 38
  • 43
  • 2
    Using int a[500] just passes a pointer to an int. Using int(&a)[500] passes a reference to an array of 500 elements. They are different types and the compiler sees the mismatch. By the way, by using int(&a)[500] you can't pass an array allocated with new int[500] any more! – rpg Sep 03 '09 at 09:24
  • Great! A useful technique. The actual generated code is identical as far as I can tell. – nimrodm Sep 03 '09 at 10:23
3

I second what rpg said. However, in case you want to call the function with arrays of any size, you could use a template to do that:

template< std::size_t N>
void getarray(int (&a)[N])
Community
  • 1
  • 1
sbi
  • 219,715
  • 46
  • 258
  • 445