在通过函数创建边缘时获得访问冲突错误

Getting Access Violation error when creating an Edge via function

本文关键字:访问冲突 错误 边缘 函数 创建      更新时间:2023-10-16

我正在实现一个用于不同程序的Graph ADT,并且我得到了这些我需要定义的"插入"answers"删除"函数。他们应该创建一个边缘(从边缘结构)与两个顶点,并插入/删除它到一个更大的图形。当我在main中创建它的实例时,它运行良好,但当我试图调用插入或删除函数时,它给出了一个错误,说:

" COMP222—Program3.exe: 0xC0000005:访问违规写入位置0xCDCDCDCD"。

关于我可能在这里做错了什么导致这个错误的想法吗?再次,主要的问题是插入/删除,但我张贴了它的其余部分,以防万一。

    EDGE STRUCT
    struct Edge { //edge with vertices v1 and v2 
    int *vertex1;
    int *vertex2;
};

 GRAPH.H
#include "Graph.h"
#include <iostream>
Graph::Graph() {
    graphSize = 0;
};
Graph::Graph(const string& file) {
    text.open(file);
    while(!text.eof()) {
    char ch;
    text.get(ch);
    vertices.push_back(ch);
}
for(int i = 0;i < sizeof(vertices);i++) {
    static_cast<int>(vertices.at(i));
}
}
void Graph::insert(int v1,int v2) {
    Edge* newEdge = new Edge;
    *newEdge->vertex1 = v1;
    *newEdge->vertex2 = v2;
    v1 = vertices.at(0);
    v2 = vertices.at(2);
    graphSize += 2;
    };
    void Graph::remove(int v1,int v2) {
        Edge* delEdge = new Edge; //edge to be deleted
    *delEdge->vertex1 = v1;
    *delEdge->vertex2 = v2;
    delete delEdge->vertex1;
    delete delEdge->vertex2;
    graphSize -= 2;
    };
    ostream& operator <<(ostream& verts,const Graph& graph) {
    return verts;
    };

 MAIN FUNCTION -- problem seems to be with the test.insert and test.remove                       functions
#include "Graph.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
    Graph test("Path to file...no problem here..."); //THIS WORKS FINE
    test.insert(2,3); //INSERT/REMOVE CAUSE THE ERROR
    test.remove(2,3);
    system("PAUSE");
    return 0;
}

问题在于插入函数中的这两行:

*newEdge->vertex1 = v1;
*newEdge->vertex2 = v2;

vertex1vertex2是未初始化的指针,它们没有指向内存中的有效位置,而您正在尝试写入这些位置。我怀疑你希望vertex1vertex2仅仅是保存顶点id的int型。

您的remove函数尝试进行类似的写入操作。