首先,这是原文(ISO/IEC 9899:2011 6.7.6.3 Semantics 7):
A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation. If the keyword static also appears within the [ and ] of the array type derivation, then for each call to the function, the value of the corresponding actual argument shall provide access to the first element of an array with at least as many elements as specified by the size expression.
为了更好地理解这个问题,我写了一些代码:
#include <stdio.h>
void f(int a[static 10][10])
{
printf("0x%p\n", a);
}
int main(int argc, char *argv[])
{
int a[][10] = {[20] = {1, 2}};
f(a);
int b[][10] = {{3, 4}};
f(b);
return 0;
}
static(int a[static 10][10]) 代表什么?
该代码的行为是否未定义?为什么?
为什么我们只需要提供对数组的第一个元素而不是全部元素的访问?
最佳答案
what is that static(int a[static 10][10]) stand for?
正如您提供的报价中所写:
... If the keyword static also appears within the [ and ] of the array type derivation, then for each call to the function, the value of the corresponding actual argument shall provide access to the first element of an array with at least as many elements as specified by the size expression.
Is the behavior of that code undefined? why?
是的,如果函数需要一个在大小表达式中具有指定数量的元素的数组,但该数组类型的相应参数具有较少的元素,则该函数的行为将是未定义的,因为该函数将尝试访问超出该大小的内存。数组中用作参数的元素数量。
Why do we only need to provide access to the first element of an array not all of it?
我们需要至少提供对大小表达式中参数声明中指定的元素数量的访问,因为它是函数和函数用户之间的契约。该函数至少需要大小表达式中指定的元素数量。
关于arrays - ISO/IEC 9899 :2011 6. 7.6.3 语义 7 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68335893/