首页 > 解决方案 > 将 char 数组添加到链表

问题描述

#include <stdio.h>
#include <stdlib.h>

typedef struct node{
    char word[20];
    struct node * next;
}node;

int main(){
    FILE *ifp;
    char newword[20];
    node * head;

    ifp = fopen("para.txt","r");
    head = (node * )malloc(sizeof(node));

    while(fscanf(ifp,"%s",newword) != EOF){
         head -> next = NULL;
         head -> word = newword;
     }

    return 0;
}

我想将文本文件读取的单词添加到链接列表中。我试图用这段代码做,但我做不到。我怎样才能解决这个问题。

标签: c

解决方案


您只需分配一个节点 ( head),然后在循环的每次迭代中更改其内容。要创建一个链表,您需要node为每个单词分配一个新的(循环的每次迭代)。这样的事情应该这样做:

int main(){
    FILE *ifp;
    char newword[20];
    node * head = NULL;
    node  *last = NULL;
    node  *current;

    ifp = fopen("para.txt","r");
    if (ifp == NULL) {
        fprintf(stderr, "Unable to open file para.txt\n");
        return EXIT_FAILURE;
    }
    while(fscanf(ifp,"%19s",newword) != EOF){
         current = malloc(sizeof(node));
         strcpy(current -> word,newword);
         if(last) {
             last->next = current;
         }
         else {
             head = current;
         }
         last = current;
    }

    return EXIT_SUCCESS;
}

推荐阅读