c++ transfer matrix to procedure ,memory leaks
i am wandering. i can't believe my eyes! if i allocate matrix in procedure input 开发者_JS百科, after exit from procedure, matrix had been deleted!
void input(int **x,int& m,int &n)
{
int i,j;
x=new int*[mx];
for(i=0;i<mx;i++)
x[i]=new int[nx];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&x[i][j]);
for(i=0;i<mx;i++)
for(j=0;j<nx;j++)
printf("%d",x[i][j]); - i see normal matrix
}
int main()
{
int **x,**y,mx,my,nx,ny;
int i,j;
input(x,mx,nx);
for(i=0;i<mx;i++)
for(j=0;j<nx;j++)
printf("%d",x[i][j]); - i receive a lot of stuff
return 0;
}
why matrix was deleted? as i understand, i transfer **x , it points to part of memory , there matrix lies. but when i have returned to main, i lost matrix, i have not deleted it. why have i lost matrix?
if i do this in main function
x=new int*[mx];
for(i=0;i<mx;i++)
x[i]=new int[nx];
all is right
x
is passed by value to input
; whatever modifications input
does to x
within itself, they won't be seen outside input
. (Hint: try to printf("%p\n", x)
inside and outside input
). So, if you want to solve it with the least modifications to your code, you have to use a triple indirection here (i.e., int ***x
) and pass &x
to input
. But this is a very C-ish way of doing things; in C++, you are most likely better off with defining your own Matrix
class and work with that.
Use
void input(int & **x,int& m,int &n)
instead of
void input(int **x,int& m,int &n)
i.e. pass x
by reference instead of by value.
void input(int **x,int& m,int &n)
{
int i,j;
x=new int*[mx];
...
Where are mx and nx coming from? From what I can tell, they are undefined.
Change int** x
to int**& x
in function input.
精彩评论