Functions accepting C / C ++ array types
G ++ seems to ignore the difference in array sizes when passing arrays as arguments. Ie following compilations without warnings even with -Wall
.
void getarray(int a[500])
{
a[0] = 1;
}
int main()
{
int aaa[100];
getarray(aaa);
}
Now I understand the basic model of passing a pointer, and obviously I could just define the function as getarray(int *a)
. However, I expected gcc to at least issue a warning when I explicitly specify the array sizes.
Is there a way to limit this limitation? (I guest boost :: array is one solution, but I have so much old code using a c-style array that got promoted to C ++ ...)
source to share
Arrays are passed as a pointer to their first argument. If size is important, you must declare the function asvoid getarray(int (&a)[500]);
C idiom must pass the size of the array as follows: void getarray (int a [], int size);
The C ++ idiom is to use std :: vector (or std :: tr1 :: array).
source to share
I second what rpg said . However, if you want to call a function with arrays of any size, you can use a template for that:
template< std::size_t N>
void getarray(int (&a)[N])
source to share