【问题标题】:How do I scan into a pointer that points to a structure pointer in c?如何扫描到指向 c 中结构指针的指针?
【发布时间】:2015-02-19 23:23:08
【问题描述】:

我不断收到段错误,我想使用双指针。我有一个指向结构指针的指针,但我不知道如何扫描指向该结构的指针的双指针。

int main(int argc, char* argv[])
{   
    if(argc != 4) // Error checks to make sure for correct number of arguments
    {
        printf("Incorrect number of arguments\n");
        return 0;
    }

    Car* garage69;
    Car** garage = &garage69;

    int length;
    int *size;
    size = &length;

    fill_garage(garage, argv[1], size);

    return 0;
}

void fill_garage(Car** garage, char* cars, int* size)
{
    FILE* input = fopen(cars, "r");

    fscanf(input, "%d", size);

    printf("this is size %d \n", *size);

    *garage = malloc(sizeof(Car)**size);

    int i;

    for(i=0; i<*size; i++)
    {
        (*garage[i])[i].make = malloc(sizeof(char)*MAX_STRING_LEN);
        (*garage[i]).model = malloc(sizeof(char)*MAX_STRING_LEN);
        fscanf(input, "%d %s %s %d", (*garage[i]).year, (*garage[i]).make, 
          (*garage[i]).model, (*garage[i]).miles);

    }

    fclose(input);
}

【问题讨论】:

    标签: c syntax double-pointer


    【解决方案1】:
    (*garage[i])[i].make = malloc(sizeof(char)*MAX_STRING_LEN);
    

    应该是

    (*garage)[i].make = malloc(sizeof(char)*MAX_STRING_LEN);
    

    另外,fill_garage() 可能是更简洁的设计 返回Car *,而不是返回void并使用Car **参数来接收返回值..

    【讨论】:

      猜你喜欢
      • 2021-07-14
      • 1970-01-01
      • 2010-09-25
      • 1970-01-01
      • 1970-01-01
      • 2017-01-04
      • 2016-08-25
      • 1970-01-01
      相关资源
      最近更新 更多