Question 6.14

How can I set an array's size at run time?
How can I avoid fixed-sized arrays?


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 = (int *)malloc(10 * sizeof(int));
(and if the call to malloc succeeds), you can reference dynarray[i] (for i from 0 to 9) just as if dynarray were a conventional, statically-allocated array (int a[10]). See also question 6.16.


Read sequentially: prev next up top


This page by Steve Summit // Copyright 1995 // mail feedback