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

3

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


(说明:此处的“括号”指代代码中数组或矩阵的表示方式,如Python中的列表或Numpy中的数组等。)
#include <stdio.h>
//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

谢谢

1个回答

5

在内存中,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个整数,那么matrix[2][1]在地址matrix + (2 * 5) + 1处, 我必须沿着5列走两次才能到达第三行,然后再进入该行一个元素以获取该列。如果没有第二个维度的大小,我就无法确定值将出现在内存中的位置。(在这种情况下,“我”是指编译器/运行时)

1
谢谢 @ryan-haining!你帮我理解了。 - Marco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接