-4
Rao (2012, p. 180, listing 8.9)说:“您创建的10号线的副本的原因是,这样的循环修改指针正在通过增量运算符(++
)。通过新的需要返回原来的指针用来存放完好相应delete[]
在第26行需要使用新返回的地址来调用,而不是任何随机值“。当我修改,修改和删除原始指针时,是否需要指针副本?
0: #include <iostream>
1: using namespace std;
2:
3: int main()
4: {
5: cout << “How many integers you wish to enter? “;
6: int InputNums = 0;
7: cin >> InputNums;
8:
9: int* pNumbers = new int [InputNums]; // allocate requested integers
10: int* pCopy = pNumbers;
11:
12: cout<<“Successfully allocated memory for “<<InputNums<< “ integers”<<endl;
13: for(int Index = 0; Index < InputNums; ++Index)
14: {
15: cout << “Enter number “<< Index << “: “;
16: cin >> *(pNumbers + Index);
17: }
18:
19: cout << “Displaying all numbers input: “ << endl;
20: for(int Index = 0, int* pCopy = pNumbers; Index < InputNums; ++Index)
21: cout << *(pCopy++) << “ “;
22:
23: cout << endl;
24:
25: // done with using the pointer? release memory
26: delete[] pNumbers;
27:
28: return 0;
29: }
是在pCopy
真的有必要吗?我错过了什么? 在下面的修改示例中,我不使用它并且delete[]
似乎正常工作。
#include <iostream>
using namespace std;
int main()
{
cout << "How many integers do you want? " << endl;
int InputN = 0;
cin >> InputN;
int* pNumbers = new int [InputN];
cout << "allocated memory for " << InputN << " integers" << endl;
for (int Idx = 0; Idx < InputN; Idx++) {
cout << "enter number for index " << Idx << endl;
cin >> *(pNumbers + Idx);
}
cout << "Display all input numbers: " << endl;
for (int Idx = 0; Idx < InputN + 2; ++Idx) {
cout << "integer with index: " << Idx << " has value " << *(pNumbers + Idx) << " and pointer: " << pNumbers + Idx << endl;
//cout << pNumbers - 50000 << " points to " << *(pNumbers - 50000) << endl;
}
delete[] pNumbers;
cout << "after the delete: " << endl;
for (int Idx = 0; Idx < InputN + 2; ++Idx) {
cout << "integer with index: " << Idx << " has value " << *(pNumbers + Idx) << " and pointer: " << pNumbers + Idx << endl;
//cout << pNumbers - 50000 << " points to " << *(pNumbers - 50000) << endl;
}
return 0;
}
代码墙请发布[MCVE] –
是的。由于报价中给出的原因。 – juanchopanza
您的版本不会修改'pNumbers',因此它不需要副本。 –