Multidimensional Variable-length Arrays

suggest change

Since C99, an array bound with automatic storage duration may be determined at run time. Such a type is a variable-length array (VLA). A function can use VLA syntax to describe a multidimensional array whose column count is supplied by a parameter:

#include <stddef.h>

double sum_matrix(size_t rows, size_t columns,
                  const double matrix[rows][columns])
{
    double sum = 0.0;

    for (size_t row = 0; row < rows; ++row) {
        for (size_t column = 0; column < columns; ++column) {
            sum += matrix[row][column];
        }
    }
    return sum;
}

As with every array parameter, the outermost array type is adjusted to a pointer type. The parameter is equivalent to:

const double (*matrix)[columns]

The column bound remains part of the pointed-to type and is needed to calculate each row's address.

The matrix storage can be allocated dynamically without creating a VLA object on the execution stack:

#include <stdint.h>
#include <stdlib.h>

void *allocate_matrix(size_t rows, size_t columns)
{
    if (rows == 0 || columns == 0
        || columns > SIZE_MAX / sizeof(double)
        || rows > SIZE_MAX / (columns * sizeof(double))) {
        return NULL;
    }
    return malloc(rows * columns * sizeof(double));
}

void example(size_t rows, size_t columns)
{
    if (rows == 0 || columns == 0) {
        return;
    }

    double (*matrix)[columns] = allocate_matrix(rows, columns);
    if (matrix == NULL) {
        return;
    }

    /* Use matrix[row][column]. */
    free(matrix);
}

This allocation is contiguous and requires one call to free. The caller must keep the same columns value when using the returned pointer.

VLA support is optional in some post-C99 language versions and implementation profiles. Check the target compiler before making it an API requirement. Also validate all run-time bounds: a VLA bound must be greater than zero whenever it is evaluated as the size of an object or complete type.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents