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

时间:2014-08-19 23:29:13

标签: c function gcc matrix parameters

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

#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 个答案:

答案 0 :(得分: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

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

相关问题