簡體   English   中英

文本文件到鏈表 C

[英]text-file to linked-list C

所以我試圖將一個文本文件保存在一個鏈表中(每個節點都包含一個單詞),這就是我到目前為止的代碼。 無論我做什么,它都不會運行。 如果可以的話請幫忙。

#include <string.h>
#include <ctype.h>
#define W 30000
#define M 35
typedef struct node {
    char * str;
    struct node * node ;
} Node;
typedef Node * ListofChar;
typedef Node * CharNode_ptr;
Node * createnode(char text[M]);
void letters(ListofChar * lst_ptr);

int main(void){
    ListofChar chars = NULL;
    letters(&chars);
    return 0;
    }

Node * createnode(char text[M]){
    CharNode_ptr newnode_ptr ;
    newnode_ptr = malloc(sizeof (Node));
    strcpy(newnode_ptr->str, text);
    printf("%s\n", newnode_ptr->str);
    newnode_ptr -> node = NULL;
    return newnode_ptr;
    }
void letters(ListofChar * lst_ptr){
    FILE *file;
    char txt[M];
    Node *ptr;
    ptr=*lst_ptr;
    file=fopen("Notebook.txt","r");
    while ((fscanf(file,"%29s",txt) != EOF)){
        if (strcmp(txt,"*")){
            (*lst_ptr)=createnode(txt);
            (*lst_ptr)->node=ptr;
            ptr=*lst_ptr;}}
    fclose(file);
    return;
    }

createnode中,您有以下幾行:

newnode_ptr = malloc(sizeof (Node));
strcpy(newnode_ptr->str, text);

由於newnode_ptr->str從未初始化,這是未定義的行為。 嘗試:

newnode_ptr = xmalloc(sizeof *newnode_ptr);
newnode_ptr->str = xstrdup(text);

其中xmallocxstrdupmallocstrdup的明顯包裝器,它們在失敗時中止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM