Search code examples
c++strong-typing

Functions accepting C/C++ array types


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


Solution

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