Q:
How can I set an array's size at run time?
How can I avoid
fixed-sized arrays?
A: The equivalence between arrays and pointers (see question 6.3) allows a pointer to malloc'ed memory to simulate an array quite effectively. After executing
#include <stdlib.h> int *dynarray; dynarray = malloc(10 * sizeof(int));(and if the call to malloc succeeds), you can reference dynarray[i] (for i from 0 to 9) almost as if dynarray were a conventional, statically-allocated array (int a[10]). The only difference is that sizeof will not give the size of the ``array'' (see question 7.28. See also questions 1.31b, 6.16, 7.7, and 7.29.