所以我試圖將一個文本檔案保存在一個鏈表中(每個節點都包含一個單詞),這就是我到目前為止的代碼。無論我做什么,它都不會運行。如果可以的話請幫忙。
#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,")s",txt) != EOF)){
if (strcmp(txt,"*")){
(*lst_ptr)=createnode(txt);
(*lst_ptr)->node=ptr;
ptr=*lst_ptr;}}
fclose(file);
return;
}
uj5u.com熱心網友回復:
在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并且在失敗時中止。xstrdupmallocstrdup
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/478764.html
