Array lengths in array parameters

2019-02-16 17:09发布

问题:

I am reading C Programming: A Modern Approach by K.N.King to learn the C programing language and the current chapter tells about functions, and also array parameters. It is explained that one can use constructs like these to express the length of array parameters:

1.

void myfunc(int a, int b, int[a], int[b], int[*]); /* prototype */

void myfunc(int a, int b, int n[a], int m[b], int c[a+b+other_func()]) {
... /* body */
}

2.

void myfunc(int[static 5]); /* prototype */

void myfunc(int a[static 5]) {
... /* body */
}

So the question(s) are:

a. Are the constructs in example 1 purely cosmetic or do they have an effect on the compiler?

b. Is the static modifier in this context only of cosmetic nature? what exactly does it mean and do?

c. Is it also possible to declare an array parameter like this; and is it as cosmetic as example 1 is?

void myfunc(int[4]);

void myfunc(int a[4]) { ... }

回答1:

The innermost dimension of function array parameters is always rewritten to a pointer, so the values that you give there don't have much importance, unfortunately. This changes for multidimensional arrays: starting from the second dimension these are then used by the compiler to compute things like A[i][j].

The static in that context means that a caller has to provide at least as many elements. Most compilers ignore the value itself. Some recent compilers deduce from it that a null pointer is not allowed as an argument and warn you accordingly, if possible.

Also observe that the prototype may have * so clearly the value isn't important there. In case of multidimensional arrays the concrete value is the one computed with the expression for the definition.