我的目标是编写一个简单的代码,以查找矩阵中所有行的总和。为此,我制作了一个函数sum(int c int x[])
。在此函数中,第一个参数是列数,第二个参数是一维数组。第二个参数应该一次接收矩阵的特定行,这样我就可以计算它的元素之和。
对于第一行,输出是正确的,但是从第二行开始,输出是垃圾。
例如,如果我给出此输入矩阵...
1 2 3
4 5 6
7 8 9
...则所需的输出为:
6
15
24
但是,实际上我得到的是这样的东西:
6
2004638605
1346689939
这是我的代码:
int sum(int c, int x[c])
{
int sum = 0;
for(--c; c >= 0; c--)
sum = sum + x[c];
return sum;
}
void getMatrix(int r, int c, int x[][c])
{
int i, j;
for(i = 0; i < r; i++)
{
for(j = 0; j < c; j++)
{
printf("Enter a No. = ");
scanf("%d", &x[i][j]);
}
}
}
void display (int r, int c, int x[][c])
{
int i, j;
for(i = 0; i < r; i++)
{
for(j = 0; j < c; j++)
{
printf("%d \t", x[i][j]);
}
printf("\n");
}
}
int main()
{
int a[7][7], r, c, i;
printf("Enter the Dimensions of the Matrix: ");
scanf("%d%d", &r, &c);
getMatrix(r, c, a);
printf("SHOWING MATRIX : \n");
display(r, c, a);
for(i = 0; i < r; i++)
printf("%d \n", sum(c, a[i]));
}
我正在尝试使用TDM GCC编译器编译并运行此代码。
答案 0 :(得分:0)
该错误不在问题中可见的代码中。
由于您没有显示函数getMatrix
和display
,所以我创建了一个使用问题中显示的矩阵的最小示例。
#include <stdio.h>
int sum(int c, int x[c])
{
int sum = 0;
for(--c; c >= 0; c--)
sum = sum + x[c];
return sum;
}
int main()
{
int a[7][7] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int r = 3, c = 3, i;
for(i = 0; i < r; i++) /* since your example has 3 rows and 3 columns you would not notice the wrong loop limit here (c instead of r) */
printf("%d \n", sum(c, a[i]));
}
此打印
6
15
24
符合预期。
我猜函数getMatrix
不能将数据放入正确的数组元素中。
可能它使用指定为函数参数的行数和列数,而不是实际的数组大小int a[7][7]
。
编辑:将遗漏的函数添加到问题后,很明显getMatrix
和display
无法正确访问数组。
将函数声明为
void getMatrix(int r, int c, int x[][c])
并使用c=3
调用该函数,该函数认为您正在传递具有3列的数组,而在主体中您声明a[7][7]
具有7列。二维数组的内存位置计算需要正确的列数。
原始程序的快速解决方案是将函数声明为
void getMatrix(int r, int c, int x[][7])
和
void display (int r, int c, int x[][7])
我建议使用#define
来声明数组a
和函数自变量,而不要使用幻数7。
顺便说一句:将您的程序与该答案中的代码进行比较。我修复了printf(... sum...)
周围的循环,该循环对行而不是列进行计数。
更好的解决方案是根据行和列的数量为数组a
动态分配内存,然后自己计算索引,例如
index = selected_row * number_of_columns + selected_column;