简体   繁体   English

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

[英]Why is it necessary pass the number of columns as a function argument?

When I pass a matrix in the parameters of the function, using brackets, I need pass the numbers of columns too. 当我在函数的参数中传递矩阵时,使用括号,我也需要传递列数。 Why? 为什么?

#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 error: 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

Thanks 谢谢

In memory, the int s will be laid out contiguously. 在内存中, int将连续布局。 If you don't provide all but the first dimension, there's no way to figure out the location of the int you are requesting. 如果您不提供除第一个维度之外的所有维度,则无法确定您请求的int的位置。 if your matrix is 如果您的矩阵是

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

In memory it still appears as: 在内存中它仍然显示为:

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

if I know the second dimension has 5 int s in it, then matrix[2][1] is at address matrix + (2 * 5) + 1 , I must go in by 5 columns, two times, to get to the third row, then one more element into that row to get the column. 如果我知道第二维有5个int ,那么matrix[2][1]在地址matrix + (2 * 5) + 1 ,我必须进入5列,两次,到达第三维行,然后将另外一个元素放入该行以获取列。 Without the size of the second dimension, I have no way of figuring out where the values will appear in memory. 如果没有第二维的大小,我无法确定值将在内存中出现的位置。 (in this case "I" means the compiler/runtime) (在这种情况下,“I”表示编译器/运行时)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM