next up previous
Next: Variable-size multi-dimensional arrays Up: intro_C Previous: Recursion

Variable-size arrays

The library function malloc() can be used to allocate memory dynamically. The function free() returns the memory to the pool when you're done with it. For example, to allocate an array of $n$ doubles:

    double *myArray;
    myArray = (double *) malloc(n*sizeof(double));
    assert(myArray != NULL);
    free((void *) myArray);

The return value of malloc() is a pointer to void (i.e., a so-called ``generic'' pointer) so it must be cast to the appropriate type, in this case pointer to double. Similarly, the pointer must be recast to void * for freeing. If malloc() fails to allocate the memory (for example, if there's none left!), NULL is returned, hence the assert. Bad things happen when you operate on a NULL pointer...

Be sure to #include <stdlib.h> when using malloc().

Massimo Ricotti 2009-01-26