#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/