当你有一个指向结构指针的指针时,如何使用realloc?

chu*_*uck 5 c pointers realloc

我有这个结构数组,这个函数接受一个指向数组指针的指针.原始大小为2,所以每当达到大小时,我需要重新分配并加倍大小.当这段代码运行时,我从realloc中得到一个无效的旧大小错误.我究竟做错了什么?

  int PopulateArray(struct Inventory **inv, int *size, FILE *inputFile) {
    int count = 0;
    printf("address: %u\n", inv);
    printf("address: %u\n", **inv);
    int itemNumber;
    int quantity;
    float price;
    int month;
    int year;
    while (fscanf(inputFile, "%i %i %f %i/%i", &itemNumber,
    &quantity, &price, &month, &year) != EOF) {
      (*inv)->itemNumber = itemNumber;
      (*inv)->quantity = quantity;
      (*inv)->price = price;
      (*inv)->expDate.month = month;
      (*inv)->expDate.year = year;
      printf("count: %i  size: %i\n", count, *size);

      if (count == *size - 1) {
        inv = realloc(inv, (*size * 2 * sizeof(struct Inventory)));
        *size *= 2;
      }
      inv++;
      count++;
    }
    return count;
  }
Run Code Online (Sandbox Code Playgroud)

dbu*_*ush 4

在您的函数中,inv(大概)是指针变量的地址。它是您要传递给的变量的值realloc

*inv = realloc(*inv, (*size * 2 * sizeof(struct Inventory)));
Run Code Online (Sandbox Code Playgroud)

出于同样的原因,自增inv不会达到您的预期。

因为您需要使用realloc,所以应该使用count来引用数组。

while (fscanf(inputFile, "%i %i %f %i/%i", &itemNumber,
    &quantity, &price, &month, &year) != EOF) {
  (*inv)[count].itemNumber = itemNumber;
  (*inv)[count].quantity = quantity;
  (*inv)[count].price = price;
  (*inv)[count].expDate.month = month;
  (*inv)[count].expDate.year = year;
  printf("count: %i  size: %i\n", count, *size);

  if (count == *size - 1) {
    *inv = realloc(*inv, (*size * 2 * sizeof(struct Inventory)));
    if (*inv == NULL) {
        perror("realloc failed");
        exit(1);
    }
    *size *= 2;
  }
  count++;
}
Run Code Online (Sandbox Code Playgroud)