Skip to content
Snippets Groups Projects
Commit 5201518a authored by dario.genga's avatar dario.genga
Browse files

Add matrix clone and destroy

parent 6a5aa9a8
Branches
Tags
No related merge requests found
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
#include "matrix.h" #include "matrix.h"
int main() { int main() {
matrix mat; matrix mat, cloned;
int32_t m = 3; int32_t m = 3;
int32_t n = 4; int32_t n = 4;
int32_t s = m * n; int32_t s = m * n;
...@@ -23,6 +23,12 @@ int main() { ...@@ -23,6 +23,12 @@ int main() {
matrix_init_from_array(&mat, m, n, data, s); matrix_init_from_array(&mat, m, n, data, s);
printf("Matrix %dx%d from array\n", m, n); printf("Matrix %dx%d from array\n", m, n);
matrix_print(mat); matrix_print(mat);
matrix_clone(&cloned, mat);
printf("Cloned matrix :\n");
matrix_print(cloned);
// Free the memory
matrix_destroy(&mat);
matrix_destroy(&cloned);
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
...@@ -77,9 +77,32 @@ error_code matrix_print(const matrix mat) { ...@@ -77,9 +77,32 @@ error_code matrix_print(const matrix mat) {
return ok; return ok;
} }
void swap(int *x, int *y) error_code matrix_clone(matrix *cloned, const matrix mat) {
{ error_code code = matrix_alloc(cloned, mat.m, mat.n);
int tmp = *x; if (code == err) {
*x = *y; return err;
*y = tmp; }
for (int i = 0; i < mat.m; i++) {
for (int k = 0; k < mat.n; k++) {
cloned->data[i][k] = mat.data[i][k];
}
}
return ok;
}
error_code matrix_destroy(matrix *mat) {
// Free each row
for (int32_t i = 0; i < mat->m; i++) {
free(mat->data[i]);
}
// Free the data and reset the number of row and col
free(mat->data);
mat->m = -1;
mat->n = -1;
mat->data = NULL;
return ok;
} }
...@@ -39,6 +39,4 @@ error_code matrix_get(int32_t *elem, const matrix mat, int32_t ix, int32_t iy); ...@@ -39,6 +39,4 @@ error_code matrix_get(int32_t *elem, const matrix mat, int32_t ix, int32_t iy);
error_code matrix_set(matrix mat, int32_t ix, int32_t iy, int32_t elem); error_code matrix_set(matrix mat, int32_t ix, int32_t iy, int32_t elem);
void swap(int *x, int *y);
#endif #endif
\ No newline at end of file
File deleted
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment