[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: [OT] C programming, variable size array



>>>>> "Wesley" == Wesley J Landaker <wjl@icecavern.net> writes:

[...]

Wesley> It would be better to allocate memory in chunks, ...

Yes.  If you reallocate for every number you read, then it takes O(n^2)
time to read n numbers (assuming realloc has to relocate the data every
time).  If you make your array larger than necessary, and *double* its
capacity when it's full, then it only takes O(n) time to read n numbers.

something like: (warning: haven't tried this out)

int *array = malloc(sizeof(int));
int size = 0, capacity = 1;

while (!feof(stdin)) {
  scanf("%d", array + size);
  size++;
  if (size > capacity)
  {
    capacity *= 2;
    array = realloc(array, capacity*sizeof(int));
  }
}

-- 
Hubert Chan <hubert@uhoreg.ca> - http://www.uhoreg.ca/
PGP/GnuPG key: 1024D/124B61FA
Fingerprint: 96C5 012F 5F74 A5F7 1FF7  5291 AF29 C719 124B 61FA
Key available at wwwkeys.pgp.net.   Encrypted e-mail preferred.



Reply to: