[英]Reading words from a file to a linked list in c
我想将单词从文件读到链接列表。 当我编译它时没有错误,但是当我运行它时却给我分段错误。 这是我第一次使用链接列表,因此这可能是一个基本错误,但是我真的不明白我在做什么错。 应该从文件中读取单词,单词的位置和长度。 这就是我所拥有的:
#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;
}
链表是由指针链接的几个存储区域。 您必须使用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-> next设置为NULL,然后将curr设置为NULL。 因此,在下一个循环中,第一行curr-> word不可能,因为此NULL区域中没有word字段
这是一个示例,该函数将新节点插入列表的末尾。 在此示例中,您必须为函数赋予我称为head的第一个元素的地址(head或tail,取决于您)。
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.