简体   繁体   中英

Fixing size of array as opposed to using a pointer in C

If I have an array and all I have is an upper limit on how big the array can get, and if the number of elements that get added can be considerably smaller than this limit, is it always the right choice to declare a pointer and just reallocate extra memory whenever the array grows?

For instance, instead of declaring int a[max] I can declare a pointer int *a and than just realloc when I add elements. This would save memory. Is there any drawback to doing this?

Calling realloc on every append to your array is probably too expensive. You should keep the allocated size of your memory zone, and increase it once in a while. If oldsize is the old size, you might compute something like newsize = (5*oldsize/4+10)|0xf; since for small sizes this would grow by at least 10 elements, and for large sizes you won't lose more than about 25% of memory.

If speed is a concern, you might special-case the common small sizes, eg by declaring a local array int loc[8]; and use loc instead of a malloc -ed or calloc -ed pointer for small arrays of size <=8. You could also consider alloca(3) to allocate some small array on the stack (don't use alloca on more than a few dozens of kilobytes on current desktops), or use VLAs . You might also consider flexible array members.

Of course you should always test against failure of calls to malloc , calloc , realloc etc.... (and in general of every library function you are using). Read carefully the documentation of malloc(3)

Some drawbacks:

  • increased code complexity
  • additional failure cases ( realloc might fail)
  • possible performance loss ( realloc can be slow if the array has to be moved)

You have to check and decide if the drawbacks outweigh the benefit of using less resources in most cases. Another advantage is that you don't have to know a maximum array size in advance.

You might save memory but you will certainly affect the performances.

If you want to store elements but you does not know a priori how much, why don't you use linked list ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM