*函数参数在C中的数组索引中的含义是什么?
int function(int a[*])
Run Code Online (Sandbox Code Playgroud)
hac*_*cks 11
*内部[]仅用于声明函数原型.它是一种有效的语法.当您从原型中省略参数名称时,它非常有用,如下例所示
int function(int, int [*]);
Run Code Online (Sandbox Code Playgroud)
它告诉编译器第二个参数是VLA并且取决于第一个参数的值.在上面的例子中,不值得这样做.看一个更有用的例子
int function(int, int [][*]);
Run Code Online (Sandbox Code Playgroud)
这不可能使用VLA作为函数原型中的参数,具有未命名的参数,而不使用*内部[].
句法
1 declarator:
[...]
direct-declarator [ type-qualifier-list static assignment-expression ]
direct-declarator [ type-qualifier-listopt * ]
direct-declarator ( parameter-type-list )
direct-declarator ( identifier-listopt )
该标准的第6.7.6.2/1段规定在类似数组的声明中:
除了可选的类型限定符和关键字static之外,[和]可以分隔表达式或*.
(重点补充).同一节的第4段解释说:
如果大小是*而不是表达式,则数组类型是未指定大小的可变长度数组类型,只能在具有函数原型范围的声明或类型名称中使用
如果您的实现支持VLA,那就是您所拥有的.声明该函数接受一个参数,该参数是(指向第一个元素的指针)一个未指定长度的可变长度数组.
正如@WeatherVane在评论中观察到的那样,C2011使VLA支持可选(而在C99中它是强制性的).对于不支持VLA的实现,代码在语法上是不正确的.
您可以通过预处理器检查VLA支持,有点:
#if __STDC__
#if __STDC_VERSION__ == 199901L || ( __STDC_VERSION__ >= 201112L && ! __STDC_NO_VLA__ )
// VLAs are supported (or the implementation is non-conforming)
#else
// VLAs are not supported
// (unless the implementation provides VLAs as an extension, which could,
// under some circumstances, make it non-conforming)
#endif
#else
// a C89 or non-conforming implementation; no standard way to check VLA support
#endif
Run Code Online (Sandbox Code Playgroud)