I'm writing this simple library to deal with int matrices:
#ifndef MATRIX_H_
#define MATRIX_H_
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct Matrix Matrix;
Matrix* newMatrix(const unsigned int rows, const unsigned int columns);
void setElementAt(Matrix* self, const unsigned int row, const unsigned int column, const int value);
int getElementAt(const Matrix* self, const unsigned int row, const unsigned int column);
int getRowsNo(const Matrix* self);
int getColumnsNo(const Matrix* self);
void initMatrix(Matrix* self, int value);
#endif
#include "Matrix.h"
struct Matrix {
int* grid;
const unsigned int rowsNo;
const unsigned int columnsNo;
};
Matrix* newMatrix(const unsigned int rowsNo, const unsigned int columnsNo) {
assert(rowsNo > 0 && columnsNo > 0);
Matrix new = {
.grid = malloc(rowsNo * columnsNo * sizeof(int)),
.rowsNo = rowsNo,
.columnsNo = columnsNo
};
Matrix* self = &new;
return self;
}
int getRowsNo(const Matrix* self) {
return self->rowsNo;
}
int getColumnsNo(const Matrix* self) {
return self->columnsNo;
}
int getElementAt(const Matrix* self, const unsigned int row, const unsigned int column) {
assert(row < self->rowsNo && column < self->columnsNo);
return self->grid[row * self->rowsNo + column];
}
void setElementAt(Matrix* self, const unsigned int row, const unsigned int column, const int value) {
assert(row < self->rowsNo && column < self->columnsNo);
self->grid[row * self->rowsNo + column] = value;
}
void initMatrix(Matrix* self, int value) {
for(int row = 0; row < self->rowsNo; row++) {
for(int column = 0; column < self->columnsNo; column++) {
setElementAt(self, row, column, value);
}
}
}
The problem I'm having is that each time that the functions getElementAt()
or setElementAt()
are invoked, the columnsNo field (and only that one) of the struct Matrix instances changes to a huge random value, despite it being marked as const.
Which problem am I failing to see here?