2016-02-04 43 views
0

我試圖創建一個從.txt文件中讀取單詞的字符串列表。我的代碼只適用於.txt文件包含少量單詞時,我無法弄清楚爲什麼,我認爲這是我的代碼的內存分配問題。從.txt文件創建字符串列表

#include <stdio.h> 
#include <stdlib.h> struct s_nodo { 
    char* word; 
    struct s_nodo*sig; }; typedef struct s_nodo* t_nodo; 

void add (t_nodo*,char*); void print(t_nodo); 

int main() { 
    char aux[30]; 
    t_nodo lista=NULL; 
    FILE*fd; 
    fd=fopen("c:\\texto.txt","r"); 
    while(!feof(fd)) 
    { 
     fscanf(fd,"%s",aux); 
     add(&lista,aux); 

    } 
    print(lista); 
    return 0; } 



void add (t_nodo*lista,char *aux) { 

    if(*lista==NULL) 
    { 
     *lista=malloc(sizeof(t_nodo)); 
     (*lista)->word=malloc((strlen(aux+1))*sizeof(char)); 
     strcpy((*lista)->word,aux); 
     (*lista)->sig=NULL; 

    } 
    else add (&(*lista)->sig,aux); 

} 

void print (t_nodo lista) { 
    if(lista!=NULL) 
    { 
     printf("-%s-",lista->word); 
     print(lista->sig); 
    } 

} 

回答

1

你的編碼風格,導致這個錯誤在這裏

(*lista)->word=malloc((strlen(aux+1))*sizeof(char)); 
         //  ^
  1. 不要使用sizeof(char),因爲它是1,這就是強制性的,它只是幫你忽略了這個問題。
  2. 使用更多的空白區域,這將在你的眼睛之前輕鬆地分離令牌。
  3. 在使用指針之前,請務必檢查malloc()未返回NULL

所以應該

(*lista)->word = malloc(strlen(aux) + 1); 

現在看到它是如何清楚,不是嗎?

+0

謝謝你,現在它的工作,但我不明白爲什麼我不應該把的sizeof(炭),可你解釋我? – Marco

+0

因爲它是1.你不需要這樣做,只會讓代碼難以閱讀。 –

3

您正在爲指針結構的大小分配內存,而您需要爲結構本身的大小分配內存。

變化

*lista=malloc(sizeof(t_nodo)); 

*lista=malloc(sizeof(struct s_nodo)); 

而且,你用錯了表達分配內存以word

(*lista)->word=malloc((strlen(aux+1))*sizeof(char)); 

應該

(*lista)->word=malloc((strlen(aux) + 1); //sizeof(char) == 1 in C 

這就是說,請參閱Why is 「while (!feof (file))」 always wrong?