三年前我学习了C编程语言,现在当我在java和c#面对一些指针问题之后重新访问它时.所以我试着写一个简单的矩阵添加程序,但我不知道为什么我在打印矩阵时会得到一些奇怪的值.
码:
#include <stdio.h>
int* sumOfMat(int* m1,int* m2)
{
printf("Matrix A: \n");
printMat(m1);
printf("Matrix B: \n");
printMat(m2);
int mat3[3][3];
int row=0,col=0,k=0,sum=0;
for(;row<3;row++)
{
col=0;
for (;col<3 ;col++ )
{
sum=(*m1+*m2);
m1++;
m2++;
mat3[row][col]=sum;
}
}
printf("Result: \n");
// printMat(mat3); //this statement is giving me a correct output.
return mat3;
}
void printMat(const int m[3][3])
{
int row,col;
for (row=0;row<3 ;row++ )
{
for (col=0;col<3 ;col++ )
{
printf("%d\t",m[row][col]);
}
printf("\n");
}
}
int main(void) {
int mat1[3][3]={{1,2,3},{4,5,6},{7,8,9}};
int mat2[3][3]={{1,2,3},{4,5,6},{7,8,9}};
//add
printf("Sum of the metrices : \n");
int* x=sumOfMat(&mat1,&mat2);
printMat(x); // this call is providing me some garbage values at some locations.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Success time: 0 memory: 2292 signal:0
Sum of the metrices :
Matrix A:
1 2 3
4 5 6
7 8 9
Matrix B:
1 2 3
4 5 6
7 8 9
Result:
2 134514448 134514448
8 10 12
14 16 -1216458764
Run Code Online (Sandbox Code Playgroud)
问题:为什么我收到此错误以及如何纠正错误.
这条线
int mat3[3][3];
Run Code Online (Sandbox Code Playgroud)
在堆栈上分配您的2d数组
你正在返回一个指向这个数组的指针.
return mat3;
Run Code Online (Sandbox Code Playgroud)
不幸的是,当函数调用结束时,堆栈被解开并且数组的内存不再存在,所以你有一个指向垃圾的指针.
一种解决方案是在main函数中分配数组并将其sumOfMat作为参数传递给它.