Context
In C, I have a function which take an array as a parameter. This parameter is used as an output in this function. The output is always the same size. I would:
- make the required size clear for anyone reading the code (it will already be in the function comments, though),
- ideally the compilation to output a warning or an error so I can prevent problems at compile-time instead of run-time.
A potential solution
I found here: https://hamberg.no/erlend/posts/2013-02-18-static-array-indices.html something which look like a solution but I am not able to get a warning or an error during the compilation if I try to pass a smaller array than the required size.
Here is my complete program main.c:
void test_array(int arr[static 5]);
int main(void)
{
int array[3] = {'\0'};
test_array(array); // A warning/error should occur here at compilation-time
// telling me my array does not meet the required size.
return 0;
}
void test_array(int arr[static 5])
{
arr[2] = 0x7; // do anything...
}
Contrary to this blog, I use gcc (version 7.4.0) instead of clang with the following command:
gcc -std=c99 -Wall -o main.out main.c
In my code, we can see that the test_array() function needs a 5 elements array. I am passing a 3 elements one. I would expect a message from the compiler about this.
Question
In C, how to force a function parameter being an array to be of a given size? In case it is not, it should be noticeable at compilation-time.
staticin the array size in the parameter declaration, but compiler support for it is mostly non-existent. (Some compilers will warn if they see you pass a null pointer for such a parameter, but they otherwise neglect it.) You could pass a pointer to an array, such asint (*)[5], and this will require the caller to pass a pointer to an array of 5int, but it must be exactly 5; they could not pass an array of 6int.[and]of the array type derivation. If the keywordstaticalso appears within the[and]of the array type derivation, then for each call to the function, the value of the corresponding actual argument shall provide access to the first element of an array with at least as many elements as specified by the size expression."