我正在实现一个Graph ADT用于不同的程序,我得到了这些" insert"并且"删除"我需要定义的函数。它们应该创建一个带有两个顶点的Edge(来自Edge结构),并将其插入/移除到更大的Graph中。它在main中创建它的实例时运行正常,但是当我尝试调用insert或remove函数时,它会出现一个错误:
" COMP222中0x00A56C84处的第一次机会异常 - 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;
}
答案 0 :(得分:1)
问题应该在insert函数中使用这两行:
*newEdge->vertex1 = v1;
*newEdge->vertex2 = v2;
vertex1
和vertex2
是未初始化的指针,它们没有指向内存中的有效位置,而您正在尝试写入这些位置。我怀疑您希望vertex1
和vertex2
只是包含顶点ID的整数。
您的删除功能会尝试类似的写入。你也应该解决这个问题。