简体   繁体   English

为什么我不断收到读取访问冲突? C++

[英]Why do I keep getting a read access violation? C++

I keep running through the program and changing around pointers and I don't see what I am missing.我一直在运行程序并更改指针,但我看不到我缺少什么。 I keep getting a read access violation on line 42 of the.cpp file and I am genuinely confused on how.我一直在 .cpp 文件的第 42 行遇到读取访问冲突,我真的很困惑。

Here is the.cpp file这是.cpp文件

#include "Graph.h";

void Graph::insertEdge(int from, int to, int weight)
{
    if (from <= size && to <= size)
    {
        bool leave = true;
        EdgeNode* current = vertices[from].edgeHead;
        while (leave)
        {
            if (from == current->adjVertex || current == nullptr) //Read access violation here
            {
                current->weight = weight;
                if (current == nullptr)
                {
                    current->adjVertex = to;
                    current->nextEdge = nullptr;
                }
                leave = false;
            }
            else
                current = current->nextEdge;
        }
    }
}

and here is the.h file这是.h文件

#include "Vertex.h";
#include <fstream>;
using namespace std;

class Graph
{
    static const int MAX_VERTICES = 101;
    struct EdgeNode 
    {
        int adjVertex = 0;          
        int weight = 0;             
        EdgeNode* nextEdge = nullptr;
    };

    struct VertexNode 
    {
        EdgeNode* edgeHead = nullptr;
        Vertex* data = nullptr;         
    };

    struct Table 
    {
        bool visited;           
        int dist;               
        int path;               
    };

public:
    void buildGraph(ifstream& in);
    void insertEdge(int from, int to, int weight);
    void removeEdge(int beginning, int end);
    void findShortestPath();
    void displayAll();
    void display(int begin, int end);

private:
    int size;                   
    VertexNode vertices[MAX_VERTICES]; 
    Table T[MAX_VERTICES][MAX_VERTICES];
};

I've been on this problem for multiple hours now and I can't seem to find the issue.我已经解决这个问题好几个小时了,但我似乎找不到问题所在。

Probably instead of可能代替

 if (from == current->adjVertex || current == nullptr)

you should first ensure the pointer is not null before dereferencing it.在取消引用之前,您应该首先确保指针不是 null。

 if (current == nullptr || from == current->adjVertex)

then if current is null, the right-hand side of ||那么如果电流是 null,|| 的右侧operator won't be run.运算符不会运行。

HOWEVER, you will still have a problem because you also dereference current->weight inside the if-statement, even if current is null.但是,您仍然会遇到问题,因为您还在 if 语句中取消引用 current->weight,即使 current 是 null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM