【发布时间】:2022-11-26 15:37:05
【问题描述】:
因此,我想创建此代码以在插入之前对链表中的字符串进行排序。我无法在代码中找到错误,但每当我尝试将输入传递给插入函数时,它都会显示“分段错误(核心已转储)”——类似的内容。
我的想法是,为了排序,我会使用 strcmp() 来比较字符串,然后根据值插入。 这是代码,
struct node {
char name[50];
struct node *next;
};
struct node *insert(struct node *head, char *name) {
printf("%s NAME",
name) // To check if the string is correctly passed. Shows above error.
struct node *toinsert,*temp;
toinsert = (struct node *)malloc(sizeof(struct node));
strcpy(toinsert->name, name);
temp = head;
while (temp->next != NULL) {
int a = strcmp(temp->next->name, toinsert->name);
if (a > 0) {
break;
} else {
temp = temp->next;
}
}
toinsert->next = temp->next;
temp->next = toinsert;
return head;
}
int main() {
struct node *head = NULL;
char a[48] = "A";
head = insert(head, a);
return 0;
}
【问题讨论】:
-
我想是的,不是吗?我已将 head 定义为仅节点,并将其作为函数中的指针传递。
-
当
head为NULL时,您的代码失败。head变为temp然后立即使用。 -
缺少标头且第一个 printf() 未以“;”结尾所以这是一个语法错误
标签: c sorting data-structures linked-list singly-linked-list