鉴于,
int last(int arr[3][6]) {
return arr[2][5];
}
我想明确表示,使用
arr
关键字时 static
不能为空。int last(int arr[static 3][static 6]) {
return arr[2][5];
}
使用
gcc13 -std=c2x
我得到:
error: static or type qualifiers in non-parameter array declarator
为什么我可以做
arr[static 3][6]
而不能做 arr[static 3][static 6]
?
在声明为数组数组的参数中,C 标准仅在第一维中定义
static
,这是您需要它的唯一维度。
C 2018 6.7.6.2 1 说:
…可选类型限定符和关键字 static 只能出现在具有数组类型的函数参数的声明中,并且只能出现在最外层的数组类型派生中。
static
很有用,因为否则最外层的尺寸将会丢失。参数声明 int a[3][6]
自动调整为 int (*a)[6]
,它是一个指向 6 个 int
的数组的指针,但是没有关于该位置有多少个 6 int
的数组的信息。
int a[static 3][6]
也调整为 int (*a)[6]
,但附加信息表明该位置至少应有 3 个 6 个 int
的数组。
第二维上不需要
static
,因为第二维的信息不会丢失。 int [6]
是一个完整的类型;它是一个由 6 个 int
组成的数组。如果我们有一个指向 6 个 int
的数组的指针,那么那里就有 6 个 int
。如果我们有一个指向 3 个 6 int
的数组的指针,则那里有 3 个 6 int
的数组(总共 18 int
)。