程序崩溃(不知道)

Program crashing (No idea)

程序不断崩溃。我假设这是因为当我尝试释放内存时指针指向边界之外,但我不确定这是否真的是问题所在。有什么想法吗?

#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[] returns 的指针。你真的不应该这样做。您需要传递 delete[]new[] 分配的地址相同的地址。正如您注释掉的代码所说,您需要将指针递减回其原始值以避免崩溃。

你应该使用另一个指针来迭代你的数组,例如:

#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;
}