NL3*_*NL3 -2 c c++ pointers list
我目前正在开发一个读取数字并将其添加到链接列表的程序.
我遇到的问题是指向我的struct的指针永远不会为null,因此我不能使用if-conditions而不会遇到某种错误(SIGSEGV).
在main方法中,我创建了一个名为"head"的struct node指针:
struct node* head;
Run Code Online (Sandbox Code Playgroud)
在函数push中,我会检查head是否为null - 如果是,则表示它是未初始化的.我用正常的if条件检查了这个:
if(head == null){
//Code
}
Run Code Online (Sandbox Code Playgroud)
这从来没有奏效,if条件总是被忽略.为了解决这个问题,我引入了一个initFlag(如下面的push(...)所示),以确保在再次调用push之前用头部初始化列表(从而附加一个数字).这很有效,第一个数字已经成功推出.然而,现在,我再次遇到if-condition的问题,因此再次运行到SIGSEGV中.这里抛出错误:
while(current->next != NULL){
current = current->next;
}
Run Code Online (Sandbox Code Playgroud)
这是代码:
struct node{
int value;
struct node *next;
};
void push(int value, struct node* head, bool *initFlag){
if(!(*(initFlag))){
head = (struct node*) malloc(sizeof(struct node));
head->value=value;
head->next = NULL;
*initFlag = 1;
} else{
struct node* current = head;
while(current->next != NULL){
current = current->next;
}
current->next = (struct node*) malloc(sizeof(struct node));
current->next->value = value;
current->next->next = NULL;
}
}
Run Code Online (Sandbox Code Playgroud)