【发布时间】:2022-10-01 07:37:42
【问题描述】:
我正在尝试编写一个程序,该程序使用来自主函数参数的用户输入创建一个二维数组,然后调用一个使用指针填充该二维数组的函数。
接下来,我们调用第二个函数来打印该二维数组的所有元素。
最后,我们调用第三个函数,将数组的所有元素相加并打印总和
问题是我正在内存中的其他地方填充另一个数组,而不是主数组中的那个。所以基本上,我做了所谓的按值调用,我正在尝试按引用进行调用,但确实失败了。
这是我到目前为止所做的(有些代码可能看起来很神秘,因为它用于调试)
#include <stdio.h>
void entmat(int a ,int b, double (*M)[b])
{
int i ,j;
printf(\"entmat: %p\\n\",M);
//double** pM=M;
for (i=0 ;i<a ;i++)
{
for (j=0 ;j<b;j++)
{
printf(\"enter a value for column %d of the raw %d \",j+1,i+1);
scanf (\"%f\",*(*(M+i)+j));//*(*(M+i)+j)
printf(\"The value of the column %d of the raw %d is %f \\n\",j+1,i+1,*(*(M+i)+j));
//pM++;
}
}
}
void readmat(int a ,int b, double (*M)[b])
{
int i ,j;
printf(\"readmat: %p\\n\",M);
for (i=0 ;i<a ;i++)
{
for (j=0 ;j<b;j++)
{
printf(\"The value of the column %d of the raw %d is %f \\n\",j+1,i+1,*(*(M+i)+j));
}
}
}
void sumavr(int a ,int b, double (*M)[b])
{
int i ,j;
printf(\"sumavr: %p\\n\",M);
double avg ,s=0;
for (i=0 ;i<a ;i++)
{
for (j=0 ;j<b;j++)
{
s=s+M[i][j];
}
avg = s/j;
printf(\"the somme of the raw %d is %f and the average is %f \\n\",i,s,avg);
}
}
int main (int argc, char *argv[])
{
int a,b,i,j;
printf(\"enter the number of lignes \");
scanf(\"%d\",&a);
printf(\"enter the number of columne \");
scanf(\"%d\",&b);
double M[a][b];
printf(\"main: %p\\n\",M);
entmat(a,b,M);
for (i=0 ;i<a ;i++)
{
for (j=0 ;j<b;j++)
{
printf(\"The value of the column %d of the raw %d is %f \\n\",j+1,i+1,*(*(M+i)+j));
}
}
readmat(a,b,M);
sumavr(a,b,M);
return 0;
}
-
数组总是通过引用传递。
-
This 就是你得到的。请让你的程序通过干净
-
你不能使用
double** pM=M;。数组数组与指针数组不同。 -
我编辑了代码并做了一些改进,但它仍然不起作用
-
OT:两件事:为什么在代码处理
rows 和columns 时使用i和j?为什么不使用r和c???第二件事:累加器s需要在对下一行的值求和之前重置。否则,您可以简单地处理输入/打印函数并忽略求和,直到您了解所需的语法。
标签: arrays c pointers reference