Array lengths in array parameters

为君一笑 提交于 2019-12-30 08:15:27

问题


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.



来源:https://stackoverflow.com/questions/29895323/array-lengths-in-array-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!