我试图使用以下代码添加两个矩阵:
#include <stdio.h>
int matrix (void)
{
int a[2][2];
int b[2][2];
int c[2][2];
int i, j;
for (i = 0; i < 2; ++i) {
for (j = 0; j < 2; ++j) {
scanf("%d", &a[i][j]);
}
}
for (i = 0; i < 2; ++i) {
for (j = 0; j < 2; ++j) {
scanf("%d", &b[i][j]);
}
}
for (i = 0; i < 2; ++i) {
for (j = 0; j < 2; ++j) {
c[i][j] = a[i][j] + b[i][j];
}
}
return c;
}
int main ()
{
int i, j;
int c[2][2];
c = matrix();
for (i = 0; i < 2; ++i) {
for (j = 0; j < 2; ++j) {
printf("%d", c[i][j]);
}
printf("\n");
}
return 0;
}
上面的代码抛出了许多错误。请解释为什么编译器会显示这么多错误。
编辑-我在编译上述代码时使用了GCC4.4.3。
EDIT2-编译上述代码时出现以下错误和警告。
test.c: In function ‘matrix’:
test.c:23: warning: return makes integer from pointer without a cast
test.c:23: warning: function returns address of local variable
test.c: In function ‘main’:
test.c:29: error: incompatible types when assigning to type ‘int[2][2]’ from type ‘int’
最佳答案
你想怎么修就怎么修。
#include <stdio.h>
int (*matrix(void))[2]{//return pointer as int (*)[2]
static int c[2][2];//Can not be used to return the automatic local variables.
int a[2][2];
int b[2][2];
int i, j;
for (i = 0; i < 2; ++i) {
for (j = 0; j < 2; ++j) {
scanf("%d", &a[i][j]);
}
}
for (i = 0; i < 2; ++i) {
for (j = 0; j < 2; ++j) {
scanf("%d", &b[i][j]);
}
}
for (i = 0; i < 2; ++i) {
for (j = 0; j < 2; ++j) {
c[i][j] = a[i][j] + b[i][j];
}
}
return c;
}
int main (){
int i, j;
int (*c)[2];
c = matrix();
for (i = 0; i < 2; ++i) {
for (j = 0; j < 2; ++j) {
printf("%d ", c[i][j]);//remove &
}
printf("\n");
}
return 0;
}
关于c - 返回数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25608613/