views:

188

answers:

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++...)

+10  A: 

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
hab
rpg
Great! A useful technique. The actual generated code is identical as far as I can tell.
nimrodm
+3  A: 

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])
sbi
+1, this can be a useful approach, but be aware that you can no longer call this function with a plain `int *`!
j_random_hacker
@j_random_hacker: I actually see this as an advantage.
sbi