Reputation: 23839
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++...)
Upvotes: 2
Views: 656
Reputation: 224149
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])
Upvotes: 3
Reputation: 7787
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).
Upvotes: 10