gpt4 book ai didi

C,代码 :Block, 另一个 sigsegv,列出

转载 作者:行者123 更新时间:2023-11-30 17:29:42 25 4
gpt4 key购买 nike

大家好,从我的教授网络空间得到这个练习。我有这样的文本文件:

Simon Phillips 30
Neil Peart 45
Vinnie Colaiuta 50

我想将其存储到一个列表中,所以这是我的代码:

struct listplot {
char name[25];
char sur[25];
int age;
struct listplot *next;
};

typedef struct listplot EL;

EL *list;

int filescan(EL *current)
{
FILE *in;
int count=0;
in=fopen("persone.txt", "r");
if (ferror(in))
{
printf("File Error\n");
return count;
}
do
{
current=malloc(sizeof(EL));
fscanf(in,"%s%s%d", current->name, current->sur, &current->age);
current->next=NULL;
if (!feof(in)) count=count+filescan(current->next);
}
while (!feof(in));
return count;
}

main中我有:

int count=filescan(list);

此代码不起作用。在调试中,“do”循环似乎无限循环,但最终程序因段错误而崩溃。有人能帮我解决这个问题吗?非常感谢。

最佳答案

许多改进使其更加强大:

正确初始化此元素:

EL* list_header = NULL; /* Points to first element */

增加此处的间接级别:

int filescan(EL** current)
{

在主函数中,您必须传递list_header的地址:

count = filescan(&list_header)

将此部分移动到一个函数中,该函数唯一关心的是打开文件。

FILE *in;
int count=0;
in=fopen("persone.txt", "r");
if (ferror(in))
{
printf("File Error\n");
return count;
}

如果 in 为 NULL 或有错误,则返回 0。

do
{

首先扫描并检查是否填充了3个参数

    EL els = {0}; /* element for scanning */

if (fscanf(in,"%s%s%d", els.name, els.sur, &els.age) == 3)
{

将其移至为成功填充的 els 创建/填充/复制新 EL 的函数

current->next = create_duplicate_EL_for(els);

/* the duplicator should malloc and fill, and set next to NULL */
current=malloc(sizeof(EL));
// some strcpys //
current->next=NULL;

显然你想要计数,所以增加它。

对于循环,设置

current = current->next;

如果我们没有找到正好 3 个元素,请使用 else 完成 scanf 分支:

    else
{
/* debug/error log code here */
}
}
while (!feof(in));
return count;

关于C,代码 :Block, 另一个 sigsegv,列出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25551512/

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