[英]Program crashing (No idea)
程序不断崩溃。 我假设这是因为当我尝试释放 memory 时指针指向越界,但我不太确定这是否真的是问题所在。 任何想法?
#include <iostream>
using namespace std;
int main()
{
const int sze = 3;
int *ptr1 = new int[sze];
for (int i = 0; i < sze; i++)
{
cout << "Enter a number: ";
cin >> *(ptr1); // take the current address and place input to it
cout << ptr1 << "\n"; // just to check the address
ptr1++ ; // traverse the array
/* // remove this and the program will crash
// re-aim the pointer to the first index
if(i == 2)
{
ptr1-=3;
}
// alternative ptr1 = nullptr;
*/
}
delete [] ptr1;
您正在推进new[]
返回的指针。 你真的不应该那样做。 您需要将与new[]
分配的地址相同的地址传递给delete[]
。 正如您注释掉的代码所说,您需要将指针减回到其原始值以避免崩溃。
您应该使用另一个指针来迭代您的数组,例如:
#include <iostream>
using namespace std;
int main()
{
const int sze = 3;
int *ptr1 = new int[sze];
int *ptr2 = ptr1;
for (int i = 0; i < sze; i++)
{
cout << "Enter a number: ";
cin >> *ptr2; // take the current address and place input to it
cout << ptr2 << "\n"; // just to check the address
ptr2++ ; // traverse the array
}
delete [] ptr1;
}
或者,使用循环计数器已经提供的索引来迭代数组,例如:
#include <iostream>
using namespace std;
int main()
{
const int sze = 3;
int *ptr1 = new int[sze];
for (int i = 0; i < sze; i++)
{
cout << "Enter a number: ";
cin >> ptr1[i]; // take the current address and place input to it
cout << ptr1[i] << "\n"; // just to check the address
}
delete [] ptr1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.