Skip to content

Instantly share code, notes, and snippets.

@mateusvmv
Created June 18, 2025 19:52
Show Gist options
  • Save mateusvmv/91a8f289526be0a28dacb7d4f7877911 to your computer and use it in GitHub Desktop.
Save mateusvmv/91a8f289526be0a28dacb7d4f7877911 to your computer and use it in GitHub Desktop.
C Multi-Dimensional Array With Pointers
void *alloc_array(int ndims, const int dims[ndims], int size) {
if(ndims <= 0) exit(1);
if(ndims == 1) return calloc(dims[0], size);
int hsize = 0, n;
for(int n = 1, i = 0; i < ndims - 1; i += 1)
n *= dims[i], hsize += n;
void **head = calloc(hsize, sizeof(void*)), **ret = head;
for(n = dims[0]; ndims > 2; ndims -= 1, dims += 1) {
for(int i = 0, j = 0; i < n; i += 1, j += dims[1])
head[i] = head + n + j;
head += n, n *= dims[1];
}
void *data = calloc(n * dims[1], size);
for(int i = 0, j = 0; i < n; i += 1, j += dims[1])
head[i] = data + j * size;
return ret;
}
void free_array(void *arr, int ndims) {
if(ndims <= 0) exit(1);
if(ndims == 0) return free(arr);
void **dat = arr;
for(; ndims > 1; ndims -= 1) dat = (void**)dat[0];
free(dat), free(arr);
}
int main() {
const int X = 5, Y = 2, Z = 3, W = 2;
int ****mat = alloc_array(4, (int[4]){X, Y, Z, W}, sizeof(int));
int mat4121 = mat[4][1][2][1];
// ...
free_array(mat, 4);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment