C++ C++;尝试检查指针是否为空后获取错误
我正在用单链表写一个程序。我从链表的末尾添加元素,要做到这一点,我需要进行空检查。但在我尝试检查元素是NULL还是nullptr之后,我得到了错误。问题在C++ C++;尝试检查指针是否为空后获取错误,c++,C++,我正在用单链表写一个程序。我从链表的末尾添加元素,要做到这一点,我需要进行空检查。但在我尝试检查元素是NULL还是nullptr之后,我得到了错误。问题在中*头部检查方法?P.S.还想知道是否有更好的方法在链表中创建/插入新节点 #include <iostream> typedef struct vertex vertex; typedef struct edge edge; typedef struct vertex { int vertex; struct
中*头部
检查方法?P.S.还想知道是否有更好的方法在链表中创建/插入新节点
#include <iostream>
typedef struct vertex vertex;
typedef struct edge edge;
typedef struct vertex {
int vertex;
struct vertex * next;
edge ** head;
}vertex;
typedef struct edge {
int vertex1, vertex2;
struct edge * next;
}edge;
void add_vertex(vertex ** head, int vertex_value) {
vertex * new_vertex = new(vertex);
new_vertex->vertex = vertex_value;
if (!*head) {
new_vertex->next = NULL;
*head = new_vertex;
return;
}
vertex * tracer = *head;
while (tracer->next != NULL) {
tracer = tracer->next;
}
tracer->next = new_vertex;
new_vertex->next = NULL;
}
int main() {
vertex ** head = nullptr;
add_vertex(head, 1);
}
#包括
typedef结构顶点;
typedef结构边缘;
typedef结构顶点{
int顶点;
结构顶点*下一步;
边缘**头部;
}顶点;
typedef结构边缘{
int顶点1,顶点2;
结构边缘*下一步;
}边缘;
void add_顶点(顶点**头部,int顶点_值){
顶点*新顶点=新(顶点);
新建顶点->顶点=顶点值;
如果(!*头){
新建顶点->下一步=空;
*头=新的顶点;
返回;
}
顶点*跟踪器=*头部;
while(跟踪器->下一步!=NULL){
跟踪器=跟踪器->下一步;
}
跟踪器->下一步=新顶点;
新建顶点->下一步=空;
}
int main(){
顶点**头=空PTR;
添加_顶点(头,1);
}
我在
if(!*head)
时刻的add_vertex函数中遇到读取访问冲突错误。您正在尝试取消引用head
,该函数本身为空。
这在C++中是非法的。
在构建add_vertex
函数时,决不能将其作为head
发送空参数。
在main
中分配head
,该问题将得到解决。在main中
vertex *head = nullptr;
add_vertex(&head, 1);
这会修正你的问题,但是最好是按引用传递。
你为什么在C++中使用原始指针?BTW,在C++中你不需要<代码> TyPufFrase。对于struct vertex
,vertex
是一种类型。你可能想停留在C语言或评论一本关于C++的好书。既然你在使用C++,那么你也可以让你的生活更简单,使用<代码> STD::列表或<代码> STD::向量< /代码>,而不是创建你自己的。