代码之家  ›  专栏  ›  技术社区  ›  gberth

如何将“static”与C中的数组的数组一起使用

  •  0
  • gberth  · 技术社区  · 1 年前

    鉴于

    int last(int arr[3][6]) {
        return arr[2][5];
    }
    

    我想明确一点 arr 不能为null 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] ?

    1 回复  |  直到 1 年前
        1
  •  5
  •   Eric Postpischil    1 年前

    在声明为数组数组的参数中,C标准定义 static 只在第一个维度,这是你唯一需要它的维度。

    C 2018 6.7.6.2 1说:

    可选类型限定符和关键字static应仅出现在具有数组类型的函数参数的声明中,然后仅出现在最外层的数组类型派生中。

    静止的 是有用的,因为最外面的尺寸否则会丢失。参数声明 int a[3][6] 自动调整为 int (*a)[6] ,是指向6的数组的指针 int ,但没有关于6个数组的数量的信息 int 都在那个位置。

    int a[static 3][6] 也调整为 int(*a)[6] 但附加的信息是,应该至少有3个6的阵列 int 在那个位置。

    没有必要 静止的 因为关于第二维度的信息没有丢失。 int [6] 是一个完整的类型;它是一个6的数组 int 。如果我们有一个指向一个6的数组的指针 int ,共有6个 int 那里如果我们有一个指向三个6数组的指针 int ,有3个阵列,共6个 int 那里(18 int 全部的