为什么需要传递列数作为函数参数? [英] Why is it necessary pass the number of columns as a function argument?

查看:125
本文介绍了为什么需要传递列数作为函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  #include  
// int函数(int matrix [] [5]){//将工作
int函数(int matrix [] []){//不会工作
return matrix [ 0] [0];
}

int main(){
int matrix [5] [5];
matrix [0] [0] = 42;
printf(%d,函数(矩阵));
}

gcc错误:

< pre $ prog.c:3:18:error:数组类型有不完整的元素类型
int函数(int matrix [] []){
^
prog.c:在函数'main'中:
prog.c:10:5:error:形式参数1的类型不完整
printf(%d,function(matrix));
^
prog.c:7:被前面的错误困扰,救助

感谢

解决方案

在内存中, 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 s,那么 matrix [2] [1] 在地址矩阵+(2 * 5)+ 1 中,我必须进入5列,两次到达第三行,然后再添加一个元素进入该行以获取该列。如果没有第二维的大小,我无法确定这些值在内存中的位置。 (在这种情况下I表示编译器/运行时)


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:

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 ints will be laid out contiguously. 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. 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 ints 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. 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)

这篇关于为什么需要传递列数作为函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆