将结构的二维数组传递给函数

问题描述

我正在尝试将结构的二维数组传递给函数,但我收到了类型冲突的编译错误。 有什么帮助吗?

typedef struct{
    int height;
    int width;
} Size;

Size chart[4][4];

void compare_size(Size x[][4]){
    if(x[1][1].height > x[1][1].width)
        return 1;
}

compare_size(chart[4][4]);
error: incompatible type for argument 1 of 'compare_size'
     compare_size(chart[4][4]);
     ^
note: expected 'struct Size (*)[4]' but argument is of type 'Size'
void compare_size(Size x[][4])

解决方法

在这次通话中

compare_size(chart[4][4]);

您正在使用具有无效索引的数组 chart 的元素。

你必须写

compare_size(chart);

前提是 chart 确实是在其他地方声明的数组。

在这种情况下,表达式图表被隐式转换为指向其 Size ( * )[4] 类型的第一个元素的指针。