0
点赞
收藏
分享

微信扫一扫

C++指针使用误区及应对方法

yellowone 2022-01-06 阅读 49

最近在使用指针的时候发现一个问题,new了一个指针p, delete 的时候报错了,具体代码如下。

/* 错误示范 */

#ifndef FLOAT
typedef float				FLOAT;
#endif
FLOAT * pMeanB2 = NULL;
pMeanB2 = new FLOAT [W];
/*....*/
for (int col = 0 ; col < xx; col++)
{

	err[col] = abs(*pMeanB2- vecObserved2[col]);
	pMeanB2++;
	//...
}
delete []pMeanB2;

/* 修正代码 */

#ifndef FLOAT
typedef float				FLOAT;
#endif
FLOAT * pMeanB2 = NULL;
pMeanB2 = new FLOAT [W];
/*....*/
FLOAT *pTEMP = pMeanB2;
for (int col = 0 ; col < xx; col++)
{
	err[col] = abs(*pTEMP - vecObserved2[col]);
	pTEMP++;
	//...
}

delete []pMeanB2;

原因分析:在new指针pMeanB2后,由于访问的原因将 pMeanB2++,这就导致该指针不再指向首地址了,所以delete该指针的时候报错;解决方法:用 一个临时指针来进行访问FLOAT *pTEMP = pMeanB2,这样指针pMeanB2指向的地址依然是该内存卡的首地址,可以正常delete。

举报

相关推荐

0 条评论