Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use realloc when you have a pointer to a pointer of a struct?

I have this array of structs and this function takes a pointer to the pointer of the array. The original size is 2, so whenever it reaches the size, I need to realloc and double the size. When this code runs, I get an invalid old size error from the realloc. What am I doing wrong?

  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;
  }
like image 692
chuck Avatar asked Dec 13 '16 20:12

chuck


1 Answers

In your function, inv is (presumably) the address of a pointer variable. Its the value of that variable you want to pass to realloc.

*inv = realloc(*inv, (*size * 2 * sizeof(struct Inventory)));

For the same reason, incrementing inv itself won't do what you expect.

Because you need to use realloc, you should use count to reference the array.

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++;
}
like image 199
dbush Avatar answered Sep 21 '22 03:09

dbush