数组类型在传递给函数时会衰减为指针类型
这意味着
int func(int x[*p])
*p
不应被计算,因为该声明相当于 int func(int *x)
同样的情况也适用于指向数组的指针吗?
这是代码
int *p=0;
void func(int (*ptr)[*p]) //A
{
// code
}
int main()
{
int arr[5][5];
func(arr);
}
标准是否保证 //A
处的 *p
的评估?
我在 g++4.6 上尝试过优化和不优化。启用优化后,我不会出现段错误。在 clang 上,即使没有任何优化,代码也不会给出任何段错误。
最佳答案
摘自 C99 标准第 6.7.5.2 节数组声明符,第 1 段:
- In addition to optional type qualifiers and the keyword static, the [ and ] may delimit an expression or *. If they delimit an expression (which specifies the size of an array), the expression shall have an integer type. If the expression is a constant expression, it shall have a value greater than zero. The element type shall not be an incomplete or function type. The optional type qualifiers and the keyword static shall appear only in a declaration of a function parameter with an array type, and then only in the outermost array type derivation.
表达式*p
的计算结果为0,不满足上段的要求,因此行为未定义。
关于c - 数组指针及相关表达式求值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9470648/