You need to allocate space for the matrix. Simply assigning values to m.elements[i][j]
will do attempt to access memory at unknown locations, as m.elements
will be uninitialized and will have essentially random values. Your program may not be able to access it, or it might not be aligned properly. Build a function to create a rows
× cols
matrix:
// Initialize and return a passed-in matrix.
// matrix must point to an allocated struct, not NULL.
void build(Matrix * const matrix, const size_t rows, const size_t cols) {
matrix->rows = rows;
matrix->cols = cols;
matrix->elements = malloc(rows * sizeof(int *));
for (size_t row = 0; row < rows; row++) {
matrix->elements[row] = malloc(cols * sizeof(int));
}
}
Note that you can create arrays of any shape. If you need to create symmetric matrices, you need only store items not below the main diagonal.
Since this dynamically allocates the 2-dimensional array, it's your responsibility to free
it when you are done:
void destroy(Matrix * const matrix) {
for (size_t row = 0; row < matrix->rows; row++) {
free(matrix->elements[row]);
}
free(matrix->elements);
}