我有这个c ++代码,我的想法是:
删除指向'temp'的指针,以便'list'是唯一的指针。
#include <iostream>
using namespace std;
int main()
{
int* list = new int[1]; // create 'list' which contains int 3.
list[0] = 3;
int* temp = new int[2]; // create 'temp' which is 1 element bigger than 'list'.
for (int i = 0; i < 1; i++) { // carry over the elements of 'list' to 'temp'.
temp[i] = list[i];
}
temp[1] = 4; // add extra element to 'temp'
delete[] list; // delete contents of 'list'.
list = temp; // let 'list' point to 'temp'.
// How to delete pointer that points to 'temp' so that 'list' is the only pointer?
return 0;
}
提前谢谢。
答案 0 :(得分:0)
正如其他人提到的那样,没有必要删除指针,就像不需要删除int一样,只要你不再需要它就可以忽略它。
但是你仍然可以使用范围摆脱它:
#include <iostream>
using namespace std;
int main()
{
int* list = new int[1]; // create 'list' which contains int 3.
list[0] = 3;
//Open new scope.
{
int* temp = new int[2]; // create 'temp' which is 1 element bigger than 'list'.
for (int i = 0; i < 1; i++) { // carry over the elements of 'list' to 'temp'.
temp[i] = list[i];
}
temp[1] = 4; // add extra element to 'temp'
delete[] list; // delete contents of 'list'.
list = temp; // let 'list' point to 'temp'.
// Close the scope. tmp does not exist anymore after this. Trying to use temp after this point will result in a compilation error.
}
//does not work anymore:
//temp = nullptr;
return 0;
}