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