Skip to content

Instantly share code, notes, and snippets.

@mateusvmv
Created June 18, 2025 20:04
Show Gist options
  • Save mateusvmv/ef4ecd7356ad2880cdc9c1c4aae5025c to your computer and use it in GitHub Desktop.
Save mateusvmv/ef4ecd7356ad2880cdc9c1c4aae5025c to your computer and use it in GitHub Desktop.
C Multi-Dimensional Array With Indexing Function
void *array_alloc(int ndims, const int dims[ndims], int size) {
int n = 1;
for(int i = 0; i < ndims; i += 1)
n *= dims[i];
return calloc(n, size);
}
int array_idx(int ndims, const int dims[ndims], const int idx[ndims]) {
int i = 0, s = 1;
for(int j = ndims - 1; j >= 0; j -= 1)
i += idx[j] * s, s *= dims[j];
return i;
}
int main() {
const int X = 5, Y = 2, Z = 3, W = 2;
int *mat = array_alloc(4, (int[4]){X, Y, Z, W}, sizeof(int));
int mat4121 = mat[array_idx(4, (int[4]){X, Y, Z, W}, (int[4]){4, 1, 2, 1})];
// Or define a macro
#define I5232(mat, x, y, z, w) mat[array_idx(4, (int[4]){5, 2, 3, 2}, (int[4]){x, y, z, w})]
int mat4111 = I5232(mat, 4, 1, 1, 1);
// ...
free(mat);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment