clearmatrix & matrix add korrigiert -> tests runnen
This commit is contained in:
parent
3546fa435f
commit
55603bf12c
32
matrix.c
32
matrix.c
@ -28,10 +28,18 @@ Matrix createMatrix(unsigned int rows, unsigned int cols)
|
|||||||
|
|
||||||
void clearMatrix(Matrix *matrix)
|
void clearMatrix(Matrix *matrix)
|
||||||
{
|
{
|
||||||
free(matrix->buffer); //gibt den heap speicher frei
|
// Sicherheits-Check für den übergebenen Zeiger
|
||||||
matrix->buffer = NULL; //zeiger auf NULL setzen
|
if (matrix != NULL)
|
||||||
|
{
|
||||||
|
// **WICHTIGE KORREKTUR:** Puffer-Check vor free()
|
||||||
|
if (matrix->buffer != NULL) {
|
||||||
|
free(matrix->buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
matrix->buffer = NULL; // Zeiger auf NULL setzen
|
||||||
matrix->rows = 0;
|
matrix->rows = 0;
|
||||||
matrix->cols = 0;
|
matrix->cols = 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, unsigned int colIdx)
|
void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, unsigned int colIdx)
|
||||||
@ -55,7 +63,7 @@ Matrix add(const Matrix matrix1, const Matrix matrix2)
|
|||||||
|
|
||||||
if (matrix1.rows != matrix2.rows || matrix1.cols != matrix2.cols)
|
if (matrix1.rows != matrix2.rows || matrix1.cols != matrix2.cols)
|
||||||
{
|
{
|
||||||
Matrix result;
|
Matrix result = {0}; // Struktur auf 0/NULL initialisieren
|
||||||
result.rows = 0;
|
result.rows = 0;
|
||||||
result.cols = 0;
|
result.cols = 0;
|
||||||
result.buffer = NULL;
|
result.buffer = NULL;
|
||||||
@ -64,18 +72,20 @@ Matrix add(const Matrix matrix1, const Matrix matrix2)
|
|||||||
|
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
//Matrix result ist die neue Matrix für das Ergebnis
|
// **WICHTIGE KORREKTUR:** Speicher für das Ergebnis reservieren
|
||||||
Matrix result;
|
Matrix result = createMatrix(matrix1.rows, matrix1.cols);
|
||||||
result.rows = matrix1.rows;
|
|
||||||
result.cols = matrix1.cols;
|
|
||||||
//TODO: Chat sagt hier noch buffer calloc rein
|
|
||||||
|
|
||||||
|
// Prüfen, ob Speicherreservierung erfolgreich war
|
||||||
|
if (result.buffer == NULL) {
|
||||||
|
return result; // Gibt Null-Matrix zurück, falls malloc fehlschlug
|
||||||
|
}
|
||||||
|
|
||||||
//Addition der beiden Matrizen
|
// Addition der beiden Matrizen
|
||||||
for (int i = 0; i < result.rows * result.cols; i++)
|
for (unsigned int i = 0; i < result.rows * result.cols; i++)
|
||||||
{
|
{
|
||||||
|
// Achtung: Wenn Sie die Matrizen nicht per const Pointer übergeben,
|
||||||
|
// müssen Sie wissen, dass die Daten nicht temporär sind (hier ok, da lokale Kopien).
|
||||||
result.buffer[i] = matrix1.buffer[i] + matrix2.buffer[i];
|
result.buffer[i] = matrix1.buffer[i] + matrix2.buffer[i];
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user