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

标签 c linked-list segmentation-fault codeblocks

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

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/

相关文章:

c - 打印文件中的子字符串

c++ - 将全局变量添加到静态库以进行版本控制?

c - 如何仅针对某些子进程等待()并防止僵尸

c - 程序进入无限循环而不是调用函数?

java - java中的复制方法

python - OS X UDP 发送错误 : 55 No buffer space available

algorithm - 用链表解决hash冲突,下一步怎么识别item

c - 我如何检查c程序中的目录是否存在并在不存在时创建它

c - Shellcode 未运行

检查字符串是否是字谜