C function declaration

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

can we declare a function in a header file in following way?

extern int ap( char[][] );

can we use char[][] in function?

回答1:

For a two dimensional array, you have to supply a size for the last dimension otherwise the compiler doesn't know how to use it. (it's fine to omit the name though.)

like this:

extern int ap( char[][10] );


回答2:

No, you need to specify the last N-1 dimensions for an array.

extern int ap( char[][DIMENSION] );

For more information look here



回答3:

char[][] is not a valid array type because you cannot have arrays of an incomplete type, and char[] is incomplete. I know that's confusing because you really have two array types, so here's another example with the same problem: char a[3][]. The array a has length 3 and element type of char[], but char[] is, again, incomplete and this is invalid.

When you have a "multidimentional array", you really have an array of arrays. For example, typedef int U[3][5]; makes U an array of length 3 of arrays of length 5 of ints and is equivalent to typedef int H[5]; typedef H U[3];.

The reason you may omit the leftmost dimension with function parameters is because, with function parameters only, array types of the form T[N] are transformed into T*, and N can be left out, giving T[] to T*. This only applies at the "topmost" or "outermost" level.

So, all these function declarations are identical:

int f1(int a[3][5]); int f2(int a[][5]); int f3(int (*a)[5]); typedef int T[5]; int f4(T a[3]); int f5(T a[]); int f6(T* a);

You can, of course, delete the parameter name a in any of the above declarations without changing them.



回答4:

Yet, it is perfectly valid to omit parameter names in function declarations. When you define the function, however, you must give the array a name, and then you can refer to it by this name.



回答5:

No, this is not allowed - it attempts to declare the parameter as a pointer to an incomplete array type.

The array type must be completed with a size, like this:

extern int ap( char[][10] );


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