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);
}
}
謝謝你,現在它的工作,但我不明白爲什麼我不應該把的sizeof(炭),可你解釋我? – Marco
因爲它是1.你不需要這樣做,只會讓代碼難以閱讀。 –