2

全部。

在阅读了分段错误之后,我仍然无法弄清楚这个错误来自哪里。我知道它来自这个特定的功能;我的驱动程序中的其他所有内容都可以正常工作。

值得注意的是,所有样式都是枚举数据类型 StyleT。

被调用的函数:

openList(&list, "List.txt");

函数定义:

void openList(VehicleListT *list, char *infilename)
{   
    FILE *infile;
    int i = 0;
    char styleString[20];

    newList(list);

    if((infile = fopen(infilename, "r")) == NULL)
    {
        fprintf(stderr, "ERROR: Cannot open source file!\n");
        exit(1);
    }

    fscanf(infile, "%s\n", list->vehicles[i].vin);
    while(!feof(infile))
    {
        fscanf(infile, "%i\n", list->vehicles[i].year);
        fscanf(infile, "%lf\n", list->vehicles[i].price);
        fscanf(infile, "%s\n", list->vehicles[i].make);

        fscanf(infile, "%s\n", styleString);

        if((strcmp(styleString, "TWO_DOOR")) == 0)
        {
            list->vehicles[i].style = TWO_DOOR;
        }
        if((strcmp(styleString, "FOUR_DOOR")) == 0)
        {
            list->vehicles[i].style = FOUR_DOOR;
        }

        if((strcmp(styleString, "CONVERTIBLE")) == 0)
        {
        list->vehicles[i].style = CONVERTIBLE;
        }

        if((strcmp(styleString, "TRUCK")) == 0)
        {
                list->vehicles[i].style = TRUCK;
        }

        if((strcmp(styleString, "SUV")) == 0)
        {
            list->vehicles[i].style = SUV;
        }

        fscanf(infile, "%s\n", list->vehicles[i].color);
        fscanf(infile, "%s\n", list->vehicles[i].vin);

        i++;
        list->count++;
    }

    fclose(infile);
    return;
}
4

2 回答 2

1

在其他问题中,由于我没有完整的代码,我无法找出其中一个明显的错误,它会给您的程序带来分段错误是

fscanf(infile, "%i\n", list->vehicles[i].year);
fscanf(infile, "%lf\n", list->vehicles[i].price);

以上几行应该是,

fscanf(infile, "%i\n",  &list->vehicles[i].year);
fscanf(infile, "%lf\n", &list->vehicles[i].price);
于 2013-04-25T02:59:07.727 回答
0

一些想法:

  • 看起来您读取了 VIN 两次(就在 while 循环之前,然后在其中)?你能跳过一行吗?
  • 字符串会溢出吗?即 30 个字符的 VIN 号码?
  • 或者你正在超越数组边界?停车场车太多?:) 我建议为此添加安全检查。或者做一个链表。

我会在 while 循环的每次迭代结束时检查数据是如何加载或打印出来的。如果“i”太大,还建议进行安全检查。

于 2013-04-25T02:49:54.303 回答