我对 c(和这个网站)相当陌生,并且遇到了很多段错误问题。我正在编写一个程序,该程序创建一个数字链接列表并按升序插入值。
void insert(struct element **head, struct element *new){
if((*head)->next == NULL && (*new).i > (*(*head)->next).i){
(*head)->next = new;
return;
}
if((*head)->next == NULL && (*new).i < (*(*head)->next).i){
new->next = (*head)->next;
*head = new;
return;
}
struct element *prev = *head;
struct element *current = (*head)->next;
while(current->next != NULL){
if((*new).i < (*current).i){
prev = current;
current = current->next;
} else if((*new).i > (*current).i){
new->next = current;
prev->next = new;
}
}
}
int main (void){
struct element **head;
int value;
printf("%s", "TEST" );
printf("%s" , "Please type in an integer value. ");
scanf("%d" , &value);
printf("%s", "TEST" );
do{
printf("%s", "TEST" );
struct element *new;
if((new = malloc(sizeof(struct element))) == NULL){
return(NULL);
}
printf("%s", "TEST" );
(*new).i = value;
printf("%s", "TEST" );
if(head == NULL){
*head = new;
printList(*head);
} else if(value <= 0){
printListBackwards(*head);
}
else {
insert(head, new);
printList(*head);
}
} while(value > 0);
我不需要关于插入或其他逻辑是否正确的帮助。我什至没有机会真正测试它,因为在提示后输入整数后,我立即得到段错误。我知道这看起来很时髦,但规范要求您使用指向结构体(链表的头)的指针。
最佳答案
您确定希望 head 成为 element**
而不是 element*
吗?这种额外的分离程度会给您带来问题,其中最重要的是代码非常难以阅读。
这是我最关心的事情:
if(head == NULL){
*head = new;
printList(*head);
}
您确认 head 是 NULL 指针,然后立即尝试使用 *
取消引用它。如果你真的坚持 head 是一个双指针,那么你需要在取消引用它之前动态分配它。就像这样:
if(head == NULL){
head = malloc(sizeof(element*));
*head = new;
printList(*head);
}
这实际上在语法上可能并不完美(我来自 C++),但你明白了。但说到 C++,在 C 中将变量命名为“new”通常被认为是不好的做法,因为 new
是 C++ 中的关键字。
关于C编程分段故障链表程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15824554/