c++ - 向量数组上的“无法访问地址处的内存”
问题描述
我正在尝试用 C++ 制作一个图表,我几乎没有代码,但我遇到了一些奇怪的错误。如果我只是运行代码,我会得到Process finished with exit code 0
.,但是如果我查看调试器(特别是,我尝试检查我的graph
对象),我会看到Cannot access memory at address 0x...
.
我是 C++ 新手,所以我无法真正理解给我这个错误的原因。另外,我几乎还没有代码,这几行是我从以前的程序中提取的,这些程序没有这个问题。
无论如何,我有一vertex
堂课:
#ifndef P2_VERTEX_H
#define P2_VERTEX_H
class vertex {
private:
int id;
public:
explicit vertex(int id) { this->id = id; }
int get_id() { return id; }
};
#endif //P2_VERTEX_H
然后是一个graph
标题:
#ifndef P2_GRAPH_H
#define P2_GRAPH_H
#include <vector>
#include "vertex.h"
class graph {
private:
int N; // number of vertices
int M; // number of edges
std::vector<vertex*> vertices; // vector of vertices
std::vector<vertex*> *adj; // ARRAY of vectors of vertices
public:
graph(int n_vert);
graph(bool from_file, const char *file_name);
};
实施graph
:
#include "graph.h"
#include <iostream>
#include <fstream>
#include <sstream>
graph::graph(int n_vert) {
N = n_vert;
}
我实例graph
化为:
#include "graph.h"
int main() {
graph g = graph(4);
return 0;
}
具体来说,如果我std::vector<vertex*> *adj;
在图表标题中取消注释,则会出现此错误。虽然我意识到这可能不是存储邻接列表的完美方式,但我不明白为什么它会给我提到的错误。特别是因为我以前使用过它,而不是std::vector<vertex*>
我有std::vector<edge*>
where edge
is some struct
。我也尝试过std::vector<vertex>
,std::vector<vertex*>
但我有同样的错误。
adj
更新:如果我在构造
函数中初始化:到达此行后adj = new std::vector<vertex*>[N];
我进入Duplicate variable object name
调试器。
解决方案
问题是您从未初始化adj
,因此它将指向内存中的随机位置。
您必须初始化指针以nullptr
摆脱它。
例如在构造函数初始化列表中:
graph::graph(int n_vert) : N(n_vert), adj(nullptr)
{}
顺便说一句,您忘记初始化其他字段成员。
推荐阅读
- java - 找不到合适的构造函数(Java)
- postgresql - Postgresql 查询 - 使用 ANY 查询和 LIKE 时返回每个结果行的所有匹配搜索词
- ios - GMSAutocompleteViewController 去掉“取消”按钮
- r - 根据 R 中的多个条件创建开始和结束时间列(dplyr,lubridate)
- c - 删除指向字符串指针的退格键的函数
- git - 如何直观地分析和跟踪 git repo 中的所有源代码和资产文件大小?
- python - 为什么从加速度转换后速度和位移会增加?
- php - 直接使用 db 行值或将 db 行值存储在 php 中的变量之间的区别
- sql - 从谷歌大查询中获取最大记录
- c++ - 如何在c ++中比较2个链表并将匹配的数据放入另一个链表