C 从.txt文件创建字符串列表
我正在尝试创建一个从.txt文件中读取单词的字符串列表。我的代码只有在.txt文件包含少量单词时才起作用,我不知道为什么,我认为这是代码内存分配的问题C 从.txt文件创建字符串列表,c,string,pointers,malloc,dynamic-memory-allocation,C,String,Pointers,Malloc,Dynamic Memory Allocation,我正在尝试创建一个从.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 pr
#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);
}
}
#包括
#包含结构s_nodo{
字符*字;
结构s_nodo*sig;};typedef结构s_nodo*t_nodo;
无效添加(t_nodo*,char*);无效打印(t_nodo);
int main(){
char-aux[30];
t_nodo lista=NULL;
文件*fd;
fd=fopen(“c:\\texto.txt”、“r”);
而(!feof(fd))
{
fscanf(fd,“%s”,辅助);
添加(&lista,aux);
}
印刷品(lista);
返回0;}
无效添加(t_nodo*lista,char*aux){
如果(*lista==NULL)
{
*lista=malloc(sizeof(t_nodo));
(*lista)->word=malloc((strlen(aux+1))*sizeof(char));
strcpy((*lista)->word,aux);
(*lista)->sig=NULL;
}
否则添加(&(*lista)->sig,aux);
}
无效打印(t_nodo lista){
if(lista!=NULL)
{
printf(“-%s-”,lista->word);
打印(列表A->sig);
}
}
您的编码风格导致了这一错误
(*lista)->word=malloc((strlen(aux+1))*sizeof(char));
// ^
sizeof(char)
,因为它是1,这是必需的,它只是帮助您忽略了这个问题malloc()
是否未返回NULL
(*lista)->word = malloc(strlen(aux) + 1);
现在明白了吧?你的编码风格导致了这个错误
(*lista)->word=malloc((strlen(aux+1))*sizeof(char));
// ^
sizeof(char)
,因为它是1,这是必需的,它只是帮助您忽略了这个问题malloc()
是否未返回NULL
(*lista)->word = malloc(strlen(aux) + 1);
现在明白了吧?您正在为指向结构的指针的大小分配内存,而您需要为结构本身的大小分配内存 改变
*lista=malloc(sizeof(t_nodo));
到
另外,您使用了错误的表达式将内存分配给word
(*lista)->word=malloc((strlen(aux+1))*sizeof(char));
应该是
(*lista)->word = malloc(strlen(aux) + 1);
(*lista)->word=malloc( (strlen(aux) + 1 ); //sizeof(char) == 1 in C
也就是说,请参见您正在为指向结构的指针的大小分配内存,而您需要为结构本身的大小分配内存 改变
*lista=malloc(sizeof(t_nodo));
到
另外,您使用了错误的表达式将内存分配给word
(*lista)->word=malloc((strlen(aux+1))*sizeof(char));
应该是
(*lista)->word = malloc(strlen(aux) + 1);
(*lista)->word=malloc( (strlen(aux) + 1 ); //sizeof(char) == 1 in C
也就是说,请看谢谢,现在它工作了,但我不明白为什么我不应该把sizeof(char)放进去,你能解释一下吗?因为它是1。您不需要这样做,这样做只会使代码很难阅读。谢谢,现在它正在工作,但我不明白为什么我不应该放sizeof(char),您能解释一下吗?因为它是1。您不需要这样做,这样做只会使代码难以阅读。