C - 在不是结构或联合和分段错误中请求成员"x"(丢失)



//目标:将文件中的数据加载到结构中

typedef struct {
        int year;
        char* make;
        char* model;
        int miles;
    } Car;
    void fill_garage(Car** garage, char* cars, int* size);
    int main(int argc, char** argv)
    {
        if(argc<3)
        {
            printf("Not enough arguments.n");
            return 0;
        }
        int size;
        Car** garage;
        fill_garage(garage, argv[1], &size);
        return 0;
    }
    void fill_garage(Car** garage, char* cars, int* size)
    {
        int i;
        FILE* inputF=fopen(cars, "r");
        fscanf(inputF, "%d", size);
        garage=malloc(sizeof(Car)*(*size));
        for(i=0; i<(*size); i++)
        {
            garage[i].make=malloc(sizeof(char)*MAX_STRING_LEN);
            garage[i].model=malloc(sizeof(char)*MAX_STRING_LEN);
            //The line below causes a segmentation fault when there are no errors
            fscanf(inputF, "%d %s %s %d", &garage[i].year, garage[i].make, garage[i].model, &garage[i].miles);
        }
    }

//我不希望任何人只给我更正的代码(尽管那会很好)如果你能指出一个资源,我可以在那里学习指针,那就太好了。如果你想看的话,这是作业单。http://pastebin.com/LNeCx70m

  1. 你必须将garage的地址传递给fill_garage(),所以这个

    Car** garage;
    fill_garage(garage, argv[1], &size);
    

    应该是

    Car *garage;
    fill_garage(&garage, argv[1], &size);
    /*          ^ pass the address of garage */
    
  2. 固定大小的字符串不需要malloc(),只需像一样重新定义结构即可

    typedef struct {
        int  year;
        char make[MAX_STRING_LEN];
        char model[MAX_STRING_LEN];
        int  miles;
    } Car;
    
  3. 检查fopen()malloc()的返回值,如果它们都失败,则返回NULL,如果未能打开文件,则会导致未定义的行为。同时检查fscanf()的返回值。

  4. 对于printf()包括stdio.h,对于malloc()包括fscanf()stdlib.h

我修复了你的代码,所以原则上不会有任何问题

#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING_LEN 128
typedef struct {
    int  year;
    char make[MAX_STRING_LEN];
    char model[MAX_STRING_LEN];
    int  miles;
} Car;
void fill_garage(Car **garage, char *cars, int *size);
int main(int argc, char** argv)
{
    if (argc < 3) 
    {
        printf("Not enough arguments.n");
        return 0;
    }
    int  size;
    Car *garage;
    fill_garage(&garage, argv[1], &size);
    return 0;
}
void fill_garage(Car **output, char *cars, int *size)
{
    int   i;
    FILE *inputF;
    Car  *garage;
    if (output == NULL)
        return;
    *output = NULL;
    inputF  = fopen(cars, "r");
    if (inputF == NULL)
        return;
    if (fscanf(inputF, "%d", size) != 1)
    {
        fclose(inputF);
        return;
    }
    garage  = malloc(sizeof(*garage) * *size);
    *output = garage;
    if (garage == NULL)
    {
        fclose(inputF);
        return;
    }
    i = 0;
    while ((i < *size) && (fscanf(inputF, "%d%127s%127s%d", &garage[i].year, garage[i].make,
                                garage[i].model, &garage[i].miles) == 4))
    {
        i += 1;
    }
}

相关内容

  • 没有找到相关文章

最新更新