C:2D数组上的嵌套循环提供了意外结果

这是问题的最小可复制示例。 故意将高度和长度作为参数(而不是计算它们)。

typedef struct
{
    int red;
} triple;

int main(void)
{
    triple array[3][3] = {
      { {.red = 10}, {.red = 40}, {.red = 70}},
      { {.red = 110}, {.red = 120}, {.red = 130}},
      { {.red = 200}, {.red = 220}, {.red = 240}}
    };

printarray(2, 2, array);
}


void printarray(int height, int length, triple array[][length])
{
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < length; j++)
        {
            printf("red score at array[%i][%i] = %i\n", i, j, array[i][j].red);
        }
    }
}

我得到的输出是: 数组[0] [0] = 10处的红色分数 数组[0] [1]处的红色分数= 40 数组[1] [0] = 70处的红色分数 数组[1] [1]上的红色分数= 110

但我期望: 数组[0] [0] = 10处的红色分数 数组[0] [1]处的红色分数= 40 数组[1] [0] = 110处的红色分数 数组[1] [1]上的红色分数= 120

2d数组的索引显然不符合我的预期,但是为什么呢?

评论
  • 时间在怂恿
    时间在怂恿 回复

    You are passing 2,2 to printarray. This is height,length.

    But, the array is defined with a length of 3. So, you must pass 3 to printarray as the length.

    Otherwise, the indexing in printarray is incorrect. As you have it, the array within printarray is equivalent to triple array[2][2] and not triple array[3][3] as is required.

    The height can be less than the defined height, but length must match. Here, length is the stride. This is the number of elements in a given row.

    So, in main, call with: printarray(3,3,array)

    If you truly wish to print a subsection of the array, you'd need to pass a separate variable to printarray for the stride.

    该函数必须声明为:

    void printarray(int height, int length, int stride, triple array[][stride])
    

    Then, in main, call it with:

    printarray(2,2,3,array);