Last active
July 3, 2019 20:59
-
-
Save kraftwerk28/7c51451e95dae33227fe6f9c935c0c10 to your computer and use it in GitHub Desktop.
Matrix in single piese on memoty (almost)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#define PTR_SZ sizeof(void*) | |
#define INT_SZ sizeof(int) | |
struct monomtx; | |
int mmtx_get(struct monomtx*, int, int); | |
void mmtx_set(struct monomtx*, int, int, int); | |
// consider, that `m` is row count, whereaas, `n` is col count | |
struct monomtx { | |
int** row_ptrs; | |
int* data; | |
int w, h; | |
int (*get)(struct monomtx*, int, int); | |
void (*set)(struct monomtx*, int, int, int); | |
}; | |
// get data from grid | |
int mmtx_get(struct monomtx* self, int x, int y) { | |
int* row_ptr = *(self->row_ptrs + y); | |
return *(row_ptr + x * INT_SZ); | |
} | |
// get data into grid | |
void mmtx_set(struct monomtx* self, int x, int y, int data) { | |
int* row_ptr = *(self->row_ptrs + y); | |
*(row_ptr + x * INT_SZ) = data; | |
} | |
typedef struct monomtx monomtx_t; | |
// `constructor | |
monomtx_t* mmtx_new(int m, int n) { | |
monomtx_t* res = (monomtx_t*)malloc(sizeof(monomtx_t)); | |
res->h = m; | |
res->w = n; | |
res->get = &mmtx_get; | |
res->set = &mmtx_set; | |
res->row_ptrs = (int**)malloc(PTR_SZ * m); | |
res->data = (int*)malloc(INT_SZ * n * m); | |
for (int i = 0; i < m; ++i) { | |
res->row_ptrs[i] = res->data + n * INT_SZ * i; | |
} | |
return res; | |
} | |
// `destructor` | |
void mmtx_drop(monomtx_t* self) { | |
free(self->data); | |
for (int i = 0; i < self->h; ++i) | |
free(self->row_ptrs[i]); | |
free(self->row_ptrs); | |
free(self); | |
} | |
// usage | |
int main() { | |
monomtx_t* monomatrix = mmtx_new(3, 4); | |
monomatrix->set(monomatrix, 0, 0, 40); | |
printf("%d\n", monomatrix->get(monomatrix, 1, 0)); | |
mmtx_drop(monomatrix); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment