If we specify the size of the array in the function definition, it can be used for checking errors using static analysis tool. I used cppcheck tool for the following code.
#include <stdio.h>
void test(int in[3])
{
in[3] = 4;
}
The output is:
Cppcheck 2.2
[test.cpp:4]: (error) Array 'in[3]' accessed at index 3, which is out of bounds.
Done!
But, if you donot give any size, you will not get any error from cppcheck .
#include <stdio.h>
void test(int in[])
{
in[3] = 4;
}
The output is :
Cppcheck 2.2
Done!
But , in general, there is no need to specify the size of the array, in function definition. We cannot find the size of array inside another function, using sizeof operator, because only value of the pointer is copied. Hence, input of sizeof operator will be of type int* and not of type int[] (inside the function test()). So, the value of the size of array does not effect the code. See the code below :
#include <stdio.h>
int a[] = {1, 2, 3, 4, 5, 6, 7, 8};
void test(int in[8]) // Same as void test(int *arr)
{
unsigned int n = sizeof(in) / sizeof(in[0]); // sizeof(int*)/sizeof(int)
printf("Array size inside test() is %d\n", n);
}
int main()
{
unsigned int n = sizeof(a) / sizeof(a[0]); //sizeof(int[])/sizeof(int)
printf("Array size inside main() is %d\n", n);
test(a);
return 0;
}
The output is:
Array size inside main() is 8
Array size inside test() is 2
So, we need to pass the size of an array with an another variable.