Search code examples
cdynamicsize

Variable sized matrix in C


Is there any way to create a variable sized doubly-scripted array in C (not C++, just C)? I know that to create a variable sized singly-scripted array, you just use a pointer, e.g.

float *array;
array = (float *) calloc(sizeof(float), n);

creates a singly-scripted array of floats of size n. Is there something similar that I can do for doubly-scripted arrays?


Solution

  • There are no double-scripted arrays in C; there are only arrays of arrays. E.g. this:

    int a[3][3];
    

    Should read as "array of 3 arrays of 3 ints", not as "array of 3x3 ints". This is immediately visible from types of expressions - e.g. a[0] is a valid expression, and its type is int[3].

    For array types, array size is part of the type, and therefore must be known at compile-time. Therefore, while you can have a type "pointer to arrays" to make one dimension dynamic, the remaining ones would still have to be fixed:

    int (*p)[3] // pointer to arrays of 3 ints each
    

    There are two traditional workarounds:

    1. Just use a single-dimensional dynamic array of width x height elements, and calculate 1D indices from 2D coordinates as (y * width + x) yourself.

    2. Use pointer to pointers:

      int** a = malloc(sizeof(int*) * height);
      for (i = 0; i < height; ++i) a[i] = malloc(sizeof(int) * width);
      a[0][0] = 123;
      ...
      

      The problem here is that your array needs not be rectangular anymore, and you can't really enforce it. Performance-wise, it's also worse than a single contiguous block of memory.

    In C99, you can also use variable-length arrays:

    void foo(int width, int height) {
        int a[width][height];
        ...
    }