Passing multidimensional arrays to a function

suggest change

Only the outermost array dimension is adjusted when an array parameter is declared. For an array of arrays, the function must know the inner bound:

#include <stddef.h>

void clear_rows(size_t row_count, int matrix[][4])
{
    for (size_t row = 0; row < row_count; ++row) {
        for (size_t column = 0; column < 4; ++column) {
            matrix[row][column] = 0;
        }
    }
}

The parameter is adjusted to int (*matrix)[4]: a pointer to an array of four integers. The following declaration describes the same function type:

void clear_rows(size_t row_count, int (*matrix)[4]);

An int ** is not compatible with either declaration. It usually points to one or more separately stored pointers, not to contiguous rows of four integers.

For run-time dimensions, a VLA parameter can express the row width:

void clear_matrix(size_t rows, size_t columns,
                  int matrix[rows][columns]);

Place columns before matrix so it is in scope for the parameter type. This form requires implementation support for variably modified types. A flat allocation with explicit index calculations is another option.

Feedback about page:

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



Table Of Contents