Skip to main content

Handling 2D arrays in C

· One min read
ひかり
Main bloger

It is convenient to manage memory where numbers are stored by summarizing the number of rows, number of columns, and the memory itself in a structure.

#include <stdio.h>
#include <stdlib.h>

typedef struct {
float *data;
int col_size;
int row_size;
} Mat;

void MatInit(Mat *mat, int row_size, int col_size) {
mat->row_size = row_size;
mat->col_size = col_size;
mat->data = (float *)calloc(row_size * col_size, sizeof(float));
}

float *MatAt(Mat *mat, int i, int j) {
return mat->data + i * mat->col_size + j;
}

void MatFree(Mat *mat) { free(mat->data); }

int main(void) {
Mat mat;
MatInit(&mat, 30, 5); // Initialize a matrix with 30 rows and 5 columns
*MatAt(&mat, 0, 0) = 50; // Assign 50 to row 0, column 0
printf("%f\n", *MatAt(&mat, 0, 0)); // Print the value at row 0, column 0

MatFree(&mat);

return 0;
}