首页 > 解决方案 > 通过指针为布尔数组分配动态内存的段错误?

问题描述

我定义了一个类,其中一个名为“Path”的私有变量指向一个布尔数组。类定义:

class Elevator {
    public:
        Elevator();
        int Solve();
        void PrintPath();

    private:
        int lim;
        int n;
        int* w;
        int* v; 
        int** DP;
        bool* Path;    

};

和构造函数:

Elevator::Elevator ()
{
    cout << "\n\tWeight limit: "; cin >> lim;
    cout << "\n\tNumber of people: "; cin >> n;

    w = new int [n + 1];
    v = new int [n + 1];
    cout << "did w and v.\n";

    cout << "Path.\n"; 
    Path = new bool [n + 1]; // HERE 

    cout << "Does the code get here?";
    DP = new int* [n + 1];
    for (int i = 1; i <= n; i++)
    {    
        DP[i] = new int [lim + 1];
        for (int j = 0; j <= lim; j++)
                DP[i][j] = 0;
    }    
}

根据打印语句,它一直工作到我用注释“\HERE”标记的那一行。

$ ./a.out 

    Weight limit: 50

    Number of people: 3
did w and v.
Path.
Segmentation fault: 11

我不知道问题是什么,因为它适用于其他指向整数的指针。

标签: c++pointerssegmentation-fault

解决方案


推荐阅读