c - 数组指针及相关表达式求值

标签 c optimization

数组类型在传递给函数时会衰减为指针类型

这意味着

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 段:

  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/

相关文章:

algorithm - 位掩码与布隆过滤器

javascript - 为 Codewars 练习优化 JavaScript

c - C语言如何对URL进行编码?

c - 通过 epoll 使用多个文件描述符

c# - 我可以更快地复制这个数组吗?

c++ - 优化 block 位操作 : base-4 numbers

python - 寻找 n * n 网格中最大的正方形

c - c linux中客户端服务器聊天应用程序中的多线程

c - 优先级队列的两种不同定义?

c - Borland C/C++ 将 short 转换为 unsigned int