双指针与二维数组
如下代码,内存空间冲突 ,求解释
class COM{public: void initial(int h,int w,char **x);};void COM::initial(int h,int w,char **x){ int i,j; x=new char*[h]; for(i=0;i<h;i++) { x[i]=new char[w]; } for(i=0;i<h;i++) for(j=0;j<w;j++) { *(x[i]+j)=' '; }}class RETC{public: RETC(int h,int w,char s) {Height=h;Width=w;sym=s;} void PLOT(); COM c;private: int Height; int Width; char sym; char **retc;}; void RETC::PLOT(){ int i,j; c.initial(Height,Width,retc); for(i=0;i<Height;i++) { for(j=0;j<Width;j++) { cout<<*(retc[i]+j); } cout<<endl; } cin>>i;}void main(){ RETC rt=RETC(12,12,'*'); rt.PLOT();}//在堆中开辟一个4×5的二维int数组#include <stdio.h>#include <malloc.h>int **p;int i,j;void main() { p=(int **)malloc(4*sizeof(int *)); if (NULL==p) return; for (i=0;i<4;i++) { p[i]=(int *)malloc(5*sizeof(int)); if (NULL==p[i]) return; } for (i=0;i<4;i++) { for (j=0;j<5;j++) { p[i][j]=i*5+j; } } for (i=0;i<4;i++) { for (j=0;j<5;j++) { printf(" %2d",p[i][j]); } printf("\n"); } for (i=0;i<4;i++) { free(p[i]); } free(p);}// 0 1 2 3 4// 5 6 7 8 9// 10 11 12 13 14// 15 16 17 18 19
[解决办法]
void initial(int h,int w,char ** x);
现在x是一个局部与initial的局部变量,生命期仅在initial中,函数返回,x的值并没有传给retc
修改方法
1.x必须是指针的引用,表示x就是RETC中的retc,并非是retc的副本。
void initial(int h,int w,char ** &x);
2.修改函数
char** COM::initial(int h,int w,char ** x)
{
int i,j;
x=new char*[h];
for(i=0;i<h;i++)
{
x[i]=new char[w];
}
for(i=0;i<h;i++)
for(j=0;j<w;j++)
{
*(x[i]+j)='';
}
return x;
}
但是这个程序存在严重问题:new后没有delete,内存泄露了