c - 接受第一个数字后链接列表崩溃

标签 c memory linked-list

struct node
{
int value;
struct node* nextptr;
};

typedef struct node Node;
typedef struct node* Nodeptr;

Nodeptr* currentptr = NULL;
Nodeptr* previousptr = NULL;
Nodeptr* startptr =NULL;

void insertnode(int data)
{

Nodeptr newptr;
newptr = (Nodeptr)malloc(sizeof(Node));
newptr->value = data;
newptr-> nextptr = NULL;

(*currentptr) = (Nodeptr)malloc(sizeof(Node));
(*previousptr) = (Nodeptr)malloc(sizeof(Node));
(*startptr) = (Nodeptr)malloc(sizeof(Node));

if((*currentptr) == NULL)
  {
   *currentptr = newptr;
   *startptr = newptr;
  }

else
{
  (*currentptr)->nextptr = newptr;
  *previousptr = *currentptr;
  (*currentptr) = newptr;
}
 }

这是我用来创建链接列表的代码。

 for(int i=0;i<n;i++)
 {
    int num;
    scanf("%d",&num);
    insertnode(num);
  }

这用于使用 for 循环从用户获取输入。 int n 已声明并初始化。 我的程序在获得第一个输入后崩溃了。我想过内存分配问题,但这似乎并不能解决问题。 另外,我是 C 和编程新手,所以请原谅任何小错误!

最佳答案

来自您的代码:

(*currentptr) = (Nodeptr)malloc(sizeof(Node));
...

if((*currentptr) == NULL)

假设您有内存进行 malloc 并且分配有效,则后面的测试是错误的且无用

您的代码中全局性地混淆了获取/设置指针和获取/设置指向的值

My program crashes after getting the first input

关于崩溃,这只是因为当您在上面的第一行取消引用它时 currentptr 为空

S.O. 上有很多 C 语言中链表的例子。我鼓励您使用搜索

来查看它们

如果您有valgring使用它,这是一个非常有用的工具,和/或当然使用调试器

关于c - 接受第一个数字后链接列表崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54128484/

相关文章:

c - 循环链表中的队列

c++ - 转换 "application's"内存地址

c - 在链接列表中插入和删除

c - C 中的类型转换是如何实现的?

c - 64 位 GCC 上 int 的最大值是多少

c - 访问C中的外部分配空间

android - PhoneStateListener 内存泄漏 - android

java - 有什么方法可以将这个列表中的第一个和最后一个元素相乘吗?

c - 安思 C : Long Double Variable Printing Out to a Value of 0. 000000

c - "if"条件在 "for"中被忽略