为什么有必要将列数作为函数参数传递?

当我在函数的参数中传递矩阵时,使用括号,我也需要传递列数。 为什么?

#include  //int function(int matrix[][5]){ //Will work int function(int matrix[][]){ //Won't work return matrix[0][0]; } int main(){ int matrix[5][5]; matrix[0][0] = 42; printf("%d", function(matrix)); } 

gcc错误:

 prog.c:3:18: error: array type has incomplete element type int function(int matrix[][]){ ^ prog.c: In function 'main': prog.c:10:5: error: type of formal parameter 1 is incomplete printf("%d", function(matrix)); ^ prog.c:7: confused by earlier errors, bailing out 

谢谢

在内存中, int将连续布局。 如果您不提供除第一个维度之外的所有维度,则无法确定您请求的int的位置。 如果您的矩阵是

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 

在内存中它仍然显示为:

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 

如果我知道第二维有5个int ,那么matrix[2][1]在地址matrix + (2 * 5) + 1 ,我必须进入5列,两次,到达第三维行,然后将另外一个元素放入该行以获取列。 如果没有第二维的大小,我无法确定值将在内存中出现的位置。 (在这种情况下,“I”表示编译器/运行时)