### Tip 18: Declare arrays when you know their size

Part of a series of tips on POSIX and C. Start from the tip intro page, or get 21st Century C, the book based on this series.

level: still basic
purpose: save the memory register stuff for when you really need it

A tip every other day on POSIX and C. Start from the tip intro page.

You can allocate arrays to have a length determined at run time.

I point this out because it's easy to find texts that indicate that you either know the size of the array at compile time or you've gotta use malloc. But it's perfectly fine to delay initialization of the array until you find out its size. Again, this is the difference between C in the 1970s when this either-or choice was real, and the C of this millennium.

For example, here's a program (found via One Thing Well) that will allow you to run several programs from the command line in parallel. The intent of the following snippet (heavily edited by me) is to get the size of the array from the user using atoi(argv[1]) (i.e., convert the first command-line argument to an integer), and then having established that number at run-time, allocate an array of the right length.

pthread_t *threads;

int thread_count = atoi(argv[1]);