我想读取文件中的单词到链表。当我编译它没有错误,但当我运行它时,它给我分段错误。这是我第一次使用链表,所以这可能是一个基本错误,但我真的不明白我做错了什么。它应该从文件中读取单词,它的位置和长度。这就是我所拥有的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node{
int pos;
int size;
char *word;
struct node *next;
}node;
int main(int argc, char **argv){
int i = 1;
char dic[40];
FILE *fp;
struct node *head;
struct node *curr, *ptr;
head = (struct node*) malloc(sizeof (struct node));
head -> next = NULL;
curr = head;
ptr = head;
fp = fopen("prob00", "r");
while(fscanf(fp, "%s", dic) != EOF){
curr -> word = dic;
curr -> pos = i;
curr -> size = strlen(dic);
curr -> next = NULL;
curr = curr -> next;
i++;
}
while(ptr != NULL){
printf("palavra: %s \t tamanho: %d \t posicao %d\n", ptr -> word, ptr -> size, ptr -> pos);
ptr = ptr -> next;
}
return 0;
}
答案 0 :(得分:2)
链表是由指针链接的几个内存区域。您必须使用malloc()创建这些内存区域。在您的代码中,下一个元素是NULL ...它不存在
while(fscanf(fp, "%s", dic) != EOF){
curr -> word = dic;
curr -> pos = i;
curr -> size = strlen(dic);
curr -> next = NULL;
curr = curr -> next;
i++;
}
您将cur-&gt;设置为NULL,然后将curr设置为NULL。所以在下一个循环中,第一行curr-&gt; word是不可能的,因为在这个NULL区域中没有字段
这是一个示例,一个在列表末尾插入新节点的函数。在这个例子中,你必须给函数提供我称为head(头部或尾部,它取决于你)的第一个元素的地址。
void insert_at_end(struct node *head)
{
struct node *new_element;
new_element = malloc(sizeof(*new_element)); // in real life you need to check malloc's return
new_element->next = NULL; // because this is the new last element, next is NULL
// new_element->pos = x // initialize datas
// new_element->size = x
// new_element->word = x
while (head->next != NULL) // we are going to the last element in the list
head = head->next;
head->next = new_element; // connection between the last element and the new one
}