From 522ada29c60878ecd38a57bc1eb80358e12d575e Mon Sep 17 00:00:00 2001 From: silvana884 Date: Sun, 16 Nov 2025 20:47:02 +0100 Subject: [PATCH] Alle Unittests erfolgreich bestanden --- matrix.c | 40 ++++++++++++++++++++++++++-------------- 1 file changed, 26 insertions(+), 14 deletions(-) diff --git a/matrix.c b/matrix.c index ce3dfd9..9b27187 100644 --- a/matrix.c +++ b/matrix.c @@ -6,30 +6,39 @@ Matrix createMatrix(unsigned int rows, unsigned int cols) { + if(rows && cols){ Matrix matrix; matrix.rows = rows; matrix.cols = cols; matrix.buffer = malloc(rows * cols * sizeof(MatrixType)); + matrix.buffer = malloc(rows * cols * sizeof(MatrixType)); + if (!matrix.buffer) { + matrix.rows = 0; + matrix.cols = 0; + return matrix; // malloc ist fehlgeschlagen + } + + for (int i = 0; i < (rows * cols); i++) matrix.buffer[i] = 0; return matrix; + } + Matrix matrix; + matrix.rows = 0; + matrix.cols = 0; + matrix.buffer = 0; + return matrix; } - void clearMatrix(Matrix *matrix) { - int rowsM = matrix->rows; - int colsM = matrix->cols; - for(int i = 0; i < rowsM; i++) - { - for(int j = 0; j < colsM; j++) - { - matrix->buffer[i * colsM + j] = 0; - } - } + free(matrix->buffer); + matrix->buffer = NULL; + matrix->rows = 0; + matrix->cols = 0; } void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, unsigned int colIdx) @@ -39,7 +48,10 @@ void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, unsigned MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int colIdx) { - return matrix.buffer[rowIdx * matrix.cols + colIdx]; + if(rowIdx >= matrix.rows || colIdx >= matrix.cols){ + return UNDEFINED_MATRIX_VALUE; + } + return matrix.buffer[rowIdx * matrix.cols + colIdx]; } Matrix add(const Matrix matrix1, const Matrix matrix2) @@ -48,9 +60,9 @@ Matrix add(const Matrix matrix1, const Matrix matrix2) int rows2 = rows(matrix2); int cols1 = cols(matrix1); int cols2 = cols(matrix2); - if((rows1 == 1 || rows2 == 1) && cols1 == cols2) //Broadcasting + if((cols1 == 1 || cols2 == 1) && rows1 == rows2) //Broadcasting { - if(rows1 == 1) //Wenn die erste Matrix der Vektor ist + if(cols1 == 1) //Wenn die erste Matrix der Vektor ist { return broadcasting(matrix1, matrix2); } @@ -90,7 +102,7 @@ Matrix broadcasting(const Matrix vektor, const Matrix matrix) { for(int j = 0; j < colsM; j++){ wert = getMatrixAt(matrix, i, j); - koordinate = getMatrixAt(vektor, j, 0); + koordinate = getMatrixAt(vektor, i, 0); setMatrixAt((koordinate + wert), result, i, j); } }