删除指针C ++的指针

时间:2015-11-29 18:26:10

标签: c++ pointers

我遇到了问题:

有一个指针:double **p = 0; 我必须这样做:task

这是对的吗?

int main {
    double **p = new double*; 
    double value = 2;
    double *index = new double; 
    index = &value; 
    p = &index; 
    p = new double*;
    index = new double;
    delete p;
    delete index; 
    return 0;
}

1 个答案:

答案 0 :(得分:0)

我假设您只是在玩教育用指针,并且没有计划将此代码用于任何重要的事情。如果您打算使用此功能,请停止并重新考虑您的算法。几乎可以肯定不需要这么多的动态分配和指针播放。

逐行扫描代码:

01 double **p = new double*; // OK
02 double value = 2;
03 double *index = new double; // OK
04 index = &value; // BAD. memory leak. Lost pointer to the allocation from 03
05 p = &index; // BAD. memory leak. Lost pointer to the allocation from 01
06 p = new double*; // OK. pointer to local overwritten, and local will self-destruct
07 index = new double; // OK. pointer to local overwritten
08 delete p; // OK. deletes allocation from 06 
09 delete index; // OK. deletes allocation from 07
10 return 0;

修改

刚刚注意到问题陈述的链接。你应该把它变得更加明显。您所需要的只是:

double value = 2;
double * valuep = &value;
double ** p = &valuep;

根据列侬和麦卡特尼的说法,爱情。