如何通过多维数组起作用? [英] How to pass multi-dimensional array to function?
问题描述
我试图可变大小的二维数组传递给函数打印它。但是在code不显示金额的确切结果。
I am trying to pass a 2D array of variable size to a function to print it.but the code doesn't show the exact result of sum.
这是code:
#include <stdio.h>
#define ROW 5
#define COLL 5
void print_arr(int a[][COLL],int m,int n){
int i,j,sum;
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("a[%d][%d]=%d\n",i,j,a[i][j]);
}
}
}
int sum_arr(int a[][COLL],int m,int n){
int i,j,sum;
for(i=0;i<m;i++){
for(j=0;j<n;j++){
sum+=a[i][j];
}
}
return sum;
}
int main (void){
int a[ROW][COLL];
int i,j,m,n;
int sum;
printf("enter rows:");scanf("%d",&m);
printf("enter coll:");scanf("%d",&n);
for(i=0;i<m;i++){
for(j=0;j<n;j++){
printf("a[%d][%d]=",i,j);scanf("%d",&a[i][j]);
}
}
print_arr(a,m,n);
printf("\n");
sum=sum_arr(a,m,n);
printf("sum=%d\n",sum);
return 0;
}
这是code的结果。
enter rows:2
enter coll:3
a[0][0]=5
a[0][1]=8
a[0][2]=4
a[1][0]=7
a[1][1]=9
a[1][2]=6
a[0][0]=5
a[0][1]=8
a[0][2]=4
a[1][0]=7
a[1][1]=9
a[1][2]=6
sum=-1217388517
请告诉我,什么是错的code ....
please tell me what's wrong with the code....
推荐答案
您应该通过数组的第二维的确切大小的功能,不是 COLL
。将其更改为 M
(或 N
,等等)
它通过 5
数的功能,而数应 3
:)如何过,这不是主要的原因是你是code不工作,只是一个建议。
初始化变量之
。它会让你的code的工作。例如总和= 0;
如果不进行初始化,则不会得到任何编译错误,但它指向的内存位置,并读取到过那里的东西(不是有效的金额),并使用它作为对于和的初始确认金额。
所以你的阵列被添加到一个非有效的金额,这就是为什么你的code不起作用。
You should pass the exact size of the second dimension of the array to the function, not COLL
. change it to m
(or n
, whatever)
It passes the number 5
to the function while the number should be 3
:) How ever, this is not the main reason that you're code is not working, just a suggestion.
Initialize the variable sum
. It will make your code work. e.g. sum = 0;
If you don't initialize it, you won't get any compile errors, but it points to a location of memory and reads thing been there before (not a valid amount) and uses it as the initial amount of that for sum.
So your array is being added to a non-valid amount, that's why your code doesn't work.
这篇关于如何通过多维数组起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!