[英]Delete a pointer to a pointer C++
我有個問題:
有一個指針: double **p = 0;
我必須這樣做:任務
這是正確的嗎?
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;
}
我假設您只是出於教育目的而使用指針,並且沒有計划將此代碼用於任何重要的事情。 如果您打算使用它,請停止並重新考慮您的算法。 幾乎可以肯定不需要這么多動態分配和指針播放。
逐行查看代碼:
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;
那,根據列儂和麥卡特尼的說法,愛。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.