当我尝试打印我的链接列表时,我遇到了段错误。谁能解释为什么?我知道一个段错误意味着我正在访问我不应该访问的内存。我假设这意味着我没有正确设置我的指针。任何帮助都会很棒。我的代码...
#include <stdio.h>
#include <stdlib.h>
struct node
{
int val;
struct node *next;
}*head;
typedef struct node item;
int main() {
item *curr, *head;
head = NULL;
char word = 'y';
//int num[10];
//int i = 0;
while (word == 'y'){
printf("Would you like to enter an integer? (y/n) ");
scanf("%s", &word);
if(word == 'y'){
int temp = 0;
printf("Enter an integer: ");
scanf("%d", &temp);
curr = (item *)malloc(sizeof(item));
curr->val = temp;
if (head == NULL){
head = curr;
head->next = NULL;
}
else {
curr->next = head;
head = curr;
}
}
}
curr = head;
while(curr != NULL) {
printf("%d\n", curr->val); //seg fault happens here
curr = curr->next ;
}
return 0;
}