Passing two-dimensional arrays to functions

suggest change

A two-dimensional C array is an array whose elements are arrays. A function must know every dimension except the first to calculate element addresses:

void clear_matrix(size_t rows, size_t columns,
                  int matrix[rows][columns])
{
    for (size_t row = 0; row < rows; ++row) {
        for (size_t column = 0; column < columns; ++column) {
            matrix[row][column] = 0;
        }
    }
}

In this parameter declaration, matrix is adjusted to a pointer to an array of columns integers. It is not an int **; those types describe different layouts.

The variable-length-array form requires VLA support. For fixed column counts, use a constant bound. A flat allocation can instead be indexed manually when dimensions are known only at run time or VLA support is unavailable. See Using flat arrays as 2D arrays.

Feedback about page:

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



Table Of Contents