簡體   English   中英

程序崩潰(不知道)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM