c - 从文件中读取单词到c中的链表

标签 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
}

关于c - 从文件中读取单词到c中的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44162199/

相关文章:

c - 我需要遍历 getaddrinfo() 吗?

c - 在 Lua 之外使用 Lua 的哈希表是否可能/实用?

C bool 类型函数总是返回 FALSE

c - 结构体属性在多个元素上具有相同的地址

c - 使用 ftok() 重复键

c - 为什么我的程序不能将大量 (>2GB) 保存到文件中?

c - 如何初始化结构并从函数调用以在 main 中显示

c - 字符串数组链表 - 段错误

c - 从文本文件中读取并放入多二维数组中

c - 将字符串数组从 C 返回到 Fortran