这是您的代码(只是格式化并添加了缺少的右括号):
#include <stdio.h>
mat(int n, int a[][5], b[][5] )
{
int i, c[5][5];
for(i=0; i<5; i++) {
for(j=0; j<5; j++) {
c[i][j] = a[i][j] + b[i][j];
}
return c;
}
}
我编译:
$ gcc -std=c99 -Wall -Wextra -Wpedantic -Wconversion -Wno-sign-compare -Wshadow test.c -o test 我得到的第一件事是:
test.c:3:24: error: unknown type name ‘b’
mat(int n, int a[][5], b[][5] )
让我们解决这个问题(在b 和j 之前添加int):
#include <stdio.h>
mat(int n, int a[][5], int b[][5] )
{
int i, c[5][5];
for(i=0; i<5; i++) {
for(int j=0; j<5; j++) {
c[i][j] = a[i][j] + b[i][j];
}
return c;
}
}
现在我们得到:
test.c:3:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
mat(int n, int a[][5], int b[][5] )
^
test.c: In function ‘mat’:
test.c:11:10: warning: return makes integer from pointer without a cast [-Wint-conversion]
return c;
^
test.c:11:10: warning: function returns address of local variable [-Wreturn-local-addr]
test.c:3:9: warning: unused parameter ‘n’ [-Wunused-parameter]
mat(int n, int a[][5], int b[][5] )
^
test.c:13:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
那么我们得到了什么:
-
mat() 返回 int,因为它是 C99 之前的默认回退,但没有不再是标准。不过,您似乎在 Visual Studio 上进行编译,它基本上实现了 C89 + 一些 C99 以实现 C++ 兼容性——但仍然要修复它。
- 然后你返回
c,这绝对不是int的类型。
- 另外你不使用
n,我猜它的意思是行数?
- 您在第一个内部循环完成后返回——这可能不是我们想要的。
该怎么做:
通常,您通常希望调用者为结果留出空间,当您返回 c 时,它是 mat() 的本地地址,这是在 mat() 完成后发生的未定义行为。而是对mat() 使用以下声明:
void mat(int r, int c, int m1[r][c], int m2[r][c], int mr[r][c]);
其中r 是行,c 是列,m1、m2 是输入矩阵,mr 是结果矩阵。
代码将是:
void mat(int r, int c, int m1[r][c], int m2[r][c], int mr[r][c])
{
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
mr[i][j] = m1[i][j] + m2[i][j];
}
}
}
你不需要返回任何东西——你写一个调用者提供的对象(希望如此)。如果你觉得勇敢,你可以在之前检查m1 == NULL || m2 == NULL || mr == NULL。
让我们看看使用这个测试代码是如何工作的:
void print_mat(int r, int c, int m[r][c]);
int main() {
int m1[2][5] = {
{0,1,2,3,4},
{1,2,3,4,5}
};
int m2[2][5] = {
{10,11,12,13,14},
{11,12,13,14,15}
};
printf("printing matrix m1:\n");
print_mat(2,5,m1);
printf("printing matrix m1:\n");
print_mat(2,5,m2);
int c[2][5];
mat(2,5,m1,m2,c);
printf("printing matrix m1+m2:\n");
print_mat(2,5,c);
}
void print_mat(int r, int c, int m[r][c])
{
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
printf("\t%d", m[i][j]);
}
printf("\n");
}
return;
}
我明白了:
printing matrix m1:
0 1 2 3 4
1 2 3 4 5
printing matrix m1:
10 11 12 13 14
11 12 13 14 15
printing matrix m1+m2:
10 12 14 16 18
12 14 16 18 20
这正是它应该是的。
最后:
- 具体说明类型,这会有所帮助。
- 如果您不确定,请打开所有警告。
-
通常不要在子函数中获取内存,让调用者来做。
- 如果您不确定指针/数组,请尽量避免使用它们并编写易于理解的小测试用例;做研究!