【发布时间】:2019-09-16 22:32:26
【问题描述】:
我得到的错误是分段错误 11。
这个想法是将节点添加到 C 中的排序列表中
我遇到的问题是在插入第一个节点(这意味着列表不再为空)之后,我得到了错误:
inserted John
|23,John|
Segmentation fault: 11
当我尝试在列表不为空时插入新节点节点时不起作用。
这是我的代码:
typedef struct StudentListNodeStruct{
int id;
char name[32] ;
struct StudentListNodeStruct *next;
} StudentListNode;
struct StudentListNode *head = NULL;
int insertStudent(StudentListNode **list, int id, char *name){
StudentListNode *newStudent = (StudentListNode*) malloc (sizeof(StudentListNode));
strcpy((*newStudent).name, *&name);
newStudent -> next = NULL;
StudentListNode *current = head;
StudentListNode *previous;
if(findStudent(list,id,name)==0){
return(1);
}
if(head == NULL){
newStudent -> next == newStudent;
head = newStudent;
return(0);
}
//This while statement is what isn't working
while(current -> next != NULL && newStudent -> id < id){
previous = current;
current = current -> next;
}
previous -> next = newStudent;
newStudent -> next = current;
}
int findStudent(StudentListNode *list, int id, char *name){
StudentListNode *current = head;
while(current != NULL){
if(current -> id == id){
return (0);
}
current = current -> next;
}
return (1);
int printList(StudentListNode *list){
StudentListNode *temp = head;
if(temp == NULL){
printf("(empty list)\n");
}
//start from the beginning
while(temp != NULL) {
printf("|%d,%s|\n",temp->id,temp->name);
temp = temp->next;
}
}
【问题讨论】:
-
你到底在问什么?请在问题中填写您想要的内容。
-
尝试将
strcpy((*newStudent).name, *&name);更改为newStudent->name = strdup(name);。即使您没有给我们StudentListNode的定义,name字段很可能定义为char *,并且您没有分配任何空间来保存名称。函数strdup会为你分配空间。 -
@bruceg 请注意,这是假设 POSIX 可用。否则将需要
malloc和strcpy的组合。 -
它泄漏了。 (并且:
return不是函数。 -
@wildplasser
return (0);是在函数中使用 return 语句的正确方法。
标签: c list segmentation-fault