[英]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);
其中xmalloc
和xstrdup
是malloc
和strdup
的明顯包裝器,它們在失敗時中止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.