c++ - 通过指针为布尔数组分配动态内存的段错误?
问题描述
我定义了一个类,其中一个名为“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
我不知道问题是什么,因为它适用于其他指向整数的指针。
解决方案
推荐阅读
- angular - 如何在 Angular 中为组件设置背景图像?
- java - 哲学家进餐问题发生死锁时如何抛出异常?
- ios - Alamofire 5 swift 5 等待alamofire查询结果显示初始视图
- excel - excel:从单词列表中查找单元格中的单词,然后返回该单词
- python - pytest 在一个函数中模拟多个请求
- python - GIS 编程 - 不明白为什么会发生 TypeError
- vue.js - 单击其中的按钮时阻止路由器链接:VUEJS
- php - 在 PHP 中绘制垂直图表
- javascript - 如何使代码更高效、更短?
- c - 如何创建 Mosquitto MQTT 自定义插件?