c程序列表访问值段错误

标签 c list

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

typedef struct node_struct {
    int data;
    struct node_struct *next;
} node;

typedef node *list;


int main()
{
    int temp;
    list head , tempList;
    char cont = 'Y';
    head = NULL;

    do {
        printf("Enter Data\n");
        scanf("%d",&temp); fflush(stdin);
        tempList = (list)malloc(sizeof(node));
        tempList->data = temp;
        tempList->next = head->next; // This line has error
        head->next = tempList;
        printf("Do you wish to continue (Y/N)\n");
        scanf("%c", &cont); fflush(stdin);
    } while (cont == 'Y');

    return 0;
}

程序收到信号 SIGSEGV,段错误。 0x08048516 in main () at listself.c:24

我想将头指针指向最新的输入值。但是 head->next 给我段错误。

我的问题是如何实现这个逻辑?

user input 1 : 5
user input 2 : 6
user input 3 : 3

list的内部结构是这样的

头 -> 3 -> 6 -> 5

此外,while 循环在获取 cont 的值之前就退出了。可能它接受 "\n"。有什么解决办法吗?

最佳答案

在引用它之前需要分配head

此外,在将 tempList->next 设置为 head->next 之前,您需要将 head->next 设置为一个值。

所以...

head = (list)malloc(sizeof(node));
tempList = (list)malloc(sizeof(node));
head->next = NULL;
head->next = tempList;
tempList->data = temp;

关于c程序列表访问值段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26075227/

相关文章:

c++ - 如何在不递增(递减)迭代器的情况下获取 std::list 中的下一个(上一个)元素?

c - 我遇到了 "Buffer overflow-array index out of bounds"错误

c - 循环中的数组元素返回随机大数字(有时为负数)

C语言与数据结构

list - 反转Prolog中列表的最后两个元素

c++ - 无法从 "initializer list"转换

c - 用于解析的 Sscanf 分隔符

C,转换通过 void 指针传递的结构数组

python - 清除列表以删除半重复值

c - 实现循环列表以及如何删除列表中的中间节点