| How can I create variable-size arrays?

Previous | Memory, C Variables, and Pointers | Next

Q: | I need variable-size arrays, i.e. arrays which size is not known in compile time...

A:

In general, making variable-size arrays in C is extremely easy for one-dimensional arrays. Instead of

    int a[n];  // where n is not known in compile-time

you can write:

    int *a;
    ...
    a = calloc (n, sizeof (int));

The same is not-so-easy for 2-dimensional arrays (see the previous question), and quite hard (although possible) for n-dimensional arrays where n>2. To do this, you need to have nasty plays with pointers. It is even possible to make a function named `multi_dim` which creates multidimensional variable-sized arrays. I once created such routine for some internal purposes (note that it is very tricky). Principally, its usage is like this: if you want to simulate

    int a[n1][n2][n3][n4];

where n1, n2, n3 and n4 are not known apriori, you need to do:

    int ****a;  // yes, quadruple pointer!!!
    ...
    a = multi_dim (4, sizeof (int), n1, n2, n3, n4);

However, TIGCC is GNU C, and it has some extensions in addition to "standard" C. For example, it allows variable-size arrays without any tricky plays with pointers!!! (Note that this particular extension, together with a few others, has been added to standard ISO C in 1999, so it is no longer non-standard.) Try this:

    void _main(void)
    {
      int m, n, p;
      m = random (5);
      n = random (5);
      p = random (5);
      {
        int a[m][n][p];
        // do something with a
      }
    }

and you will see that it works!