结构体返回错误-C
这个程序是用 C 编写的,
它应该得到一个两个 D 数组(matrixAdd)并用 scanMtx 扫描它(扫描函数不在这里,因为代码不相关)
问题:EDMtx 函数返回扫描矩阵 1, 1,1,,1,-8,1,,1,1,1 当它返回到 main 时,它是: 0,0,0,0,0,0,junk,junk,junk
似乎有一个地址错误
我做错了什么?
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
struct matrix
{
int* ptr;
int row;
int column;
};
matrix EDMtx();
void main( int argc, char* argv[])
{
int matrixAdd[5][5]={{1,1,1,3,4},{1,1,1,3,4},{1,1,1,3,4},{1,1,1,3,4},{1,1,1,3,4}};
matrix mtx;
matrix scanMtx;
mtx.ptr=&matrixAdd[0][0];
mtx.row=5;
mtx.column=5;
scanMtx= EDMtx();
// mtx= ScanM(mtx,1,1,scanMtx);- doesn't important to you.
getchar();
}
matrix EDMtx()
{
int matrx[3][3]={{1,1,1},{1,-8,1},{1,1,1}};
matrix Mtx;
Mtx.ptr=&matrx[0][0];
Mtx.row=3;
Mtx.column=3;
return Mtx;
}
this program is written in C
it supposed to get a two D array( matrixAdd) and scan it with scanMtx (the scanning function isn't here becuase the code isn't relevant)
the problem: the EDMtx function return the scanning matrix 1,1,1,,1,-8,1,,1,1,1
when it return back to main it is : 0,0,0,0,0,0,junk,junk,junk
it seems that there is a address error
what did i do wrong?
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
struct matrix
{
int* ptr;
int row;
int column;
};
matrix EDMtx();
void main( int argc, char* argv[])
{
int matrixAdd[5][5]={{1,1,1,3,4},{1,1,1,3,4},{1,1,1,3,4},{1,1,1,3,4},{1,1,1,3,4}};
matrix mtx;
matrix scanMtx;
mtx.ptr=&matrixAdd[0][0];
mtx.row=5;
mtx.column=5;
scanMtx= EDMtx();
// mtx= ScanM(mtx,1,1,scanMtx);- doesn't important to you.
getchar();
}
matrix EDMtx()
{
int matrx[3][3]={{1,1,1},{1,-8,1},{1,1,1}};
matrix Mtx;
Mtx.ptr=&matrx[0][0];
Mtx.row=3;
Mtx.column=3;
return Mtx;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
变量
matrixAdd
和matrx
以及它们指向的内存仅具有本地作用域。如果您希望它们在从函数返回后持续存在,请将它们声明为静态
,或者重新设计您的代码逻辑。 (例如,通过使用malloc
显式分配内存)The variables
matrixAdd
andmatrx
, and the memory they point to, have local scope only. If you want them to persist after returning from a function, either declare themstatic
, or redesign your code logic. (e.g. by usingmalloc
to allocate memory explicitly)在 EDMtx 中,Mtx.ptr 指向堆栈变量。这可能正在被摧毁。如果你想交换变量的指针,它们必须位于堆上
In EDMtx, Mtx.ptr is pointed to a stack variable. This is getting destroyed probably. If you want to exchange pointers to variables they must be on the heap
matrx
是一个局部变量。因此,当返回EDMtx()
时,它就会超出范围。并且Mtx.ptr
具有局部变量matrx
的引用。因此,scnMtx
的指针成员在取消引用时获取垃圾值。 永远不要返回局部变量的引用。matrx
is a local variable. So, it goes out of scope when upon return ofEDMtx()
. And theMtx.ptr
has the reference of the local variablematrx
. And so the pointer member ofscnMtx
, is getting garbage values upon dereferencing. Never return references of a local variable.