c - C 中的段错误 11 在排序列表中插入节点

标签 c list segmentation-fault

我收到的错误是段错误 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;


}
}    

最佳答案

TL;博士:

  • 阅读 1。
  • 阅读 2。
  • 阅读解决方案
  • C 语言令人沮丧,但非常有趣。

一些事情:

  1. 您不需要强制转换 malloc 的返回值,因为它 返回一个空指针。
  2. (*newStudent).name 相当于 newStudent->name。 (IE, 取消引用 newStudent 指针并获取名称成员 StudentListNode 结构)。

你的段错误问题(我认为): “*&name”本质上是要求遵循变量名的地址。请记住, &varname 将为您提供变量 varname 的地址,而指向地址的指针在取消引用时将“遵循”变量名称下“列出”的内存中的地址。

解决方案: strcpy 接受两个参数(两个指向字符串的指针) 所以你可以发送 strcpy(newStudent->name, name)

但是在此之前,您需要在 struct newStudent 内部对字符串名称进行 malloc。

即,newStudent.name = malloc(sizeof(char)*sizeof(name)),或者因为sizeof(char) = 1, newStudent.name = malloc(sizeof(name)).

注意:如果您使用 malloc(strlen(name)),则需要考虑空终止符,即 malloc(strlen(name) + 1)。但是 sizeof 会为你计算这个。

关于c - C 中的段错误 11 在排序列表中插入节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57965158/

相关文章:

python - 为什么Python中列表转换成字典后大小会减小?

c - 双向链表C实现运行时错误

c++ - 导致段错误的简单字符串分配?

c - 在C中的函数中传递指向数组的指针

c - 访问动态分配数组的越界元素/w/o SegFault

c# - 将类加载为列表

c - 使用 Scanf 在二维数组中存储输入

c - 删除一个简单的节点并通过引用或值传递一个节点来运行

互斥锁解锁和从函数返回之间是否会出现竞争条件

java列表通过重新排列链接来移动项目