首页 > 解决方案 > 向量数组上的“无法访问地址处的内存”

问题描述

我正在尝试用 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 edgeis some struct。我也尝试过std::vector<vertex>std::vector<vertex*>但我有同样的错误。

adj更新:如果我在构造 函数中初始化:到达此行后adj = new std::vector<vertex*>[N]; 我进入Duplicate variable object name调试器。

标签: c++

解决方案


问题是您从未初始化adj,因此它将指向内存中的随机位置。
您必须初始化指针以nullptr摆脱它。

例如在构造函数初始化列表中:

graph::graph(int n_vert) : N(n_vert), adj(nullptr)
{}

顺便说一句,您忘记初始化其他字段成员。


推荐阅读