-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatrix.c
67 lines (57 loc) · 1.66 KB
/
matrix.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* Copyright © 2024 Austin Berrio
*
* @file matrix.c
*
* @brief A simple and easy to use Matrix API
*
* Only use pure C.
* Only use libraries when absolutely necessary.
*
* @note Prefixing related objects, functions, etc. assists with autocomplete.
*/
#include "matrix.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Matrix operations
matrix_t* matrix_create(size_t columns, size_t rows) {
matrix_t* matrix = (matrix_t*) malloc(sizeof(matrix_t));
if (NULL == matrix) {
fprintf(stderr, "Failed to allocate memory for matrix_t.\n");
return NULL;
}
matrix->elements = (float**) malloc(rows * sizeof(float*));
if (NULL == matrix->elements) {
fprintf(stderr, "Failed to allocate memory for matrix rows.\n");
free(matrix);
return NULL;
}
for (size_t i = 0; i < rows; ++i) {
matrix->elements[i] = (float*) malloc(columns * sizeof(float));
if (NULL == matrix->elements[i]) {
fprintf(stderr, "Failed to allocate memory for matrix columns.\n");
// Free previously allocated rows
for (size_t j = 0; j < i; ++j) {
free(matrix->elements[j]);
}
free(matrix->elements);
free(matrix);
return NULL;
}
memset(matrix->elements[i], 0, columns * sizeof(float));
}
matrix->columns = columns;
matrix->rows = rows;
return matrix;
}
void matrix_free(matrix_t* matrix) {
if (NULL == matrix) {
fprintf(stderr, "Cannot free a NULL matrix.\n");
return;
}
if (matrix->elements) {
free(matrix->elements);
}
free(matrix);
}