Using flat arrays as 2D arrays

suggest change

Often the easiest solution is to pass a 2D array as one contiguous block. Element (x, y) is stored at index y * width + x. width and height must be positive, and width * height * sizeof(double) must not wrap around size_t. A failed malloc returns a null pointer; using that pointer is undefined behavior.

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

void manipulate_matrix(double *matrix, size_t width, size_t height)
{
    size_t x, y;

    for (y = 0; y < height; y++) {
        for (x = 0; x < width; x++)
            matrix[y * width + x] *= 2.0;
    }
}

int main(void)
{
    size_t width = 4;
    size_t height = 3;
    size_t x, y;
    double *matrix;

    if (width == 0 || height > SIZE_MAX / width
        || width * height > SIZE_MAX / sizeof(double))
        return EXIT_FAILURE;

    matrix = malloc(width * height * sizeof *matrix);
    if (matrix == NULL)
        return EXIT_FAILURE;

    for (y = 0; y < height; y++) {
        for (x = 0; x < width; x++)
            matrix[y * width + x] = (x == y) ? 1.0 : 0.0;
    }

    manipulate_matrix(matrix, width, height);
    free(matrix);
    return EXIT_SUCCESS;
}

Feedback about page:

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



Table Of Contents