c - 双点列表 C

标签 c list double-pointer

我想使用双指针创建一个列表并使用 void 作为返回。

#include<stdio.h>
#include<stdlib.h>

typedef struct list{
   int value;
   struct list *next;
}*list;

void addnode(struct list **List, int number) {
   if(*List == NULL) {
      *List = (struct list*)malloc(sizeof(struct list*));
      (*List)->value = number;
      (*List)->next = NULL;
   } else {
      while((*List)->next != NULL) {
         (*List) = (*List)->next;
      } 
      *List = (struct list*)malloc(sizeof(struct list*));
      (*List)->value = number;
      (*List)->next = NULL;
   }
}

int main() {
   list List1 = NULL;

   addnode(&List1, 20);

   printf("%d \n", List1->value);

   addnode(&List1, 30);
   printf("%d \n", List1->value);
   printf("%d \n", List1->next->value);
   return 0;
}

addnode 中的第一个 if 总是被执行,但我想附加列表(如果它不为空),但它似乎永远不会工作。我还会遇到段错误,因为在最后一个 printf 中,它尝试获取列表中的下一个元素,但它从未像我想要的那样初始化。

如果一切按我想要的方式工作,我应该打印出来

 printf("%d\n", List1->value) 

20

 printf("%d\n", List1->value)

20

printf("%d\n", List1->next->value)

30

最佳答案

您传递给 malloc 的大小是错误的。

您正在分配一个结构列表,而不是结构列表*

关于c - 双点列表 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19209074/

相关文章:

c - 在 C 中使用 FastCGI 访问 PUT 或 POST 请求的主体

c - 为什么 C 程序在取消引用数组指针时会崩溃?

c++ - 从路径中提取文件名

c - 将内存分配给双指针?

c - 如何创建提示

c - 进程终止时是否保证发送 RST 数据包?

c - 从类型 'char[128]' 分配给类型 'char *' 时的类型不兼容

c# - 我如何将 Linq var 转换为列表

c# - 使用 closedXML 和 C# 将一系列单元格值放入列表中

python - 向键添加值,具体取决于该值是否在另一个键中