next up previous
Next: Random Numbers Up: intro_C Previous: Variable-size arrays

Variable-size multi-dimensional arrays

One way to allocate dynamically a $m$ by $n$ array (of doubles, say) is to first allocate space for $m$ pointers to double and then allocate $n$ doubles for each of these:

    double **myArray;
    int i;
    myArray = (double **) malloc(m*sizeof(double *));
    assert(myArray);
    for (i=0;i<m;i++) {
        myArray[i] = (double *) malloc(n*sizeof(double));
        assert(myArray[i]);
    }
    DoSomethingWith(myArray);
    for (i=0;i<m;i++)
        free((void *) myArray[i]);
    free((void *) myArray);

This naturally can be extended to any number of dimensions. Perhaps a better way is to simply allocate a single $m$ by $n$ block of memory of the appropriate storage type and access the elements using row-column formulae like $i * m + j$, where $i$ runs from 0 to $m - 1$ and $j$ runs from 0 to $n - 1$.



Massimo Ricotti 2009-01-26