简体   繁体   English

程序崩溃(不知道)

[英]Program crashing (No idea)

Program keeps crashing.程序不断崩溃。 I'm assuming it's because the pointer is pointing out of bounds when I try to deallocate the memory, but I'm not so sure if that really is the problem.我假设这是因为当我尝试释放 memory 时指针指向越界,但我不太确定这是否真的是问题所在。 Any 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;

You are advancing the pointer that new[] returns.您正在推进new[]返回的指针。 You really should not be doing that at all.你真的不应该那样做。 You need to pass delete[] the same address that new[] allocates.您需要将与new[]分配的地址相同的地址传递给delete[] As your commented out code says, you would need to decrement the pointer back to its original value to avoid the crash.正如您注释掉的代码所说,您需要将指针减回到其原始值以避免崩溃。

You should use another pointer to iterate your array, eg:您应该使用另一个指针来迭代您的数组,例如:

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

Or, iterate the array using the index already provided by your loop counter, eg:或者,使用循环计数器已经提供的索引来迭代数组,例如:

#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