在通过函数创建边缘时获得访问冲突错误
Getting Access Violation error when creating an Edge via function
我正在实现一个用于不同程序的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;
vertex1
和vertex2
是未初始化的指针,它们没有指向内存中的有效位置,而您正在尝试写入这些位置。我怀疑你希望vertex1
和vertex2
仅仅是保存顶点id的int型。
您的remove函数尝试进行类似的写入操作。
相关文章:
- 使用 EvtSetChannelConfigProperty() 函数时出现访问冲突错误
- cv::resize() 失败并出现访问冲突错误(由 NULL> 处的 <struct 引起)
- 将 std::string 作为参数从一个 DLL 传递到另一个 DLL 引发访问冲突错误
- 遵循官方 Direct2D 示例,但出现访问冲突错误
- C++ 抛出读取访问冲突错误,但我不确定为什么。平铺滑块益智游戏
- 为什么我的顶点缓冲区对象出现访问冲突错误?
- 销毁 Box2D 主体 - 读取访问冲突错误
- 编译哈希算法时出现内存访问冲突错误
- 使用glCreateBuffers时发生访问冲突错误
- 访问冲突错误在 (而 (info[x] != ))
- 反转字符串 c++ 时出现访问冲突错误
- 我无法弄清楚此访问冲突错误.有人可以在这里帮助我吗?
- 使用内存访问冲突错误
- 读取字符串的字符时出错-访问冲突错误C++
- 创建链接列表时发生访问冲突错误
- 调试优先级队列程序时出现访问冲突错误
- C++LinkedList错误:访问冲突错误
- 为什么我在用SDL2_ttf填充文本时出现访问冲突错误
- MFC:在工作线程中使用对象的成员函数时获取访问冲突错误
- 在C++中使用Box2D物理退出游戏时出现访问冲突错误