gpt4 book ai didi

c - 不将字符串从文件复制到链接列表参数

转载 作者:行者123 更新时间:2023-11-30 16:59:55 25 4
gpt4 key购买 nike

void read_names(ex6 **first)
{
FILE *fltext;
ex6 *next;
char aux[50];
next = malloc(sizeof(ex6));
if (!next)
return;
(*first) = next;
fltext = fopen(nome_fich_6a, "rt");
if (!fltext)
return;
while (!feof(fltext)) {
fscanf(fltext, "%[^\n]s\n", aux);
next->name = malloc(sizeof(char)*strlen(aux));
if (!prox->name)
return;
strcpy(next->name, aux);
while (next->prox != NULL)
next = next->prox;
}
fclose(fltext);
}

所以我正在做这个练习,当我尝试读取文本文件中保存的字符串的内容时,它只是返回到菜单,并且不会将任何内容读取到 next->name 参数中。如果有人可以帮助我解决这个错误,我将非常感激。

这是我对代码所做的更改

void read_names(ex6 **first)
{
FILE *fltext;
ex6 *next;
char aux[50];
next = malloc(sizeof(ex6));
if (!next)
return;
(*first) = next;
fltext = fopen(nome_fich_6a, "rt");
if (!fltext)
return;
while (fgets(aux, 50, fltext)) {
next->name = malloc(sizeof(char)*strlen(aux));
if (!prox->name)
return;
sscanf(aux, "%[^\n]s", next->name);
strcpy(next->name, aux);
while (next->prox != NULL)
next = next->prox;
}
fclose(fltext);
}

最佳答案

看,除了: malloc(sizeof(char)*strlen(aux)); 您正在分配不带 '\0' 的 sizof 字符串,因此您应该再分配 1 个 malloc(sizeof(char)*strlen(aux) + 1);。当您复制 aux 时,您正在覆盖未分配的下一段内存。其次,节点之间没有链接。这就是为什么

while (next->prox != NULL)
next = next->prox;

失败。尝试在 while 循环内部建立链接,这应该可以工作。我希望您将 name 变量设置为 char *

在 while 循环中,您缺少 ')'。

关于c - 不将字符串从文件复制到链接列表参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37911928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com