Skip to content

Instantly share code, notes, and snippets.

@Alwinfy
Last active March 26, 2024 17:47
Show Gist options
  • Save Alwinfy/04e5de18258d19fc00ab4a675531e8e1 to your computer and use it in GitHub Desktop.
Save Alwinfy/04e5de18258d19fc00ab4a675531e8e1 to your computer and use it in GitHub Desktop.
MANY ARRAY ONE MALLOC. NO OTHER ARRAY DO THIS FOR YOU
#include <stdio.h>
#include <stdlib.h>
extern void *alloc_nd_array(size_t, size_t, ...);
void structure_test(void) {
int i;
void **arr = alloc_nd_array(sizeof(void *), 3, 3, 2, 0);
for(i=0; i<30; i++)
printf("arr[%2d] = %18p, arr + %2d = %18p\n", i, arr[i], i, (void *)(arr + i));
free(arr);
}
void usecase(void) {
int i, j, k, l;
int ****data = alloc_nd_array(sizeof(int), 2, 3, 4, 5, 0);
for(i=0; i<2; i++)
for(j=0; j<3; j++)
for(k=0; k<4; k++)
for(l=0; l<5; l++)
data[i][j][k][l] = (i << 12) + (j << 8) + (k << 4) + l;
for(i=0; i<2; i++)
for(j=0; j<3; j++) {
for(k=0; k<4; k++)
for(l=0; l<5; l++)
printf("%04x ", data[i][j][k][l]);
puts("");
}
free(data);
}
int main(void) {
structure_test();
usecase();
exit(0);
}
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
/* Takes a varargs list of dimensions for the array, ending in 0 */
void *alloc_nd_array(size_t size, size_t first, ...) {
va_list count;
size_t last, next, totalsize, arrsize;
char **block, **bptr;
int i, dims = 0;
last = first;
totalsize = 0;
arrsize = 1;
va_start(count, first);
while ((next = va_arg(count, size_t))) {
dims++;
arrsize *= last;
totalsize += arrsize;
last = next;
}
va_end(count);
block = bptr = malloc(totalsize * sizeof(void *) + arrsize * last * size);
last = first;
arrsize = 1;
va_start(count, first);
while ((next = va_arg(count, size_t))) {
size_t offset = next * (--dims ? sizeof(void *) : size);
arrsize *= last;
*bptr = (char *)(bptr + arrsize);
for (i = 1; i < arrsize; i++) {
bptr[i] = bptr[i - 1] + offset;
}
bptr = (char **)(*bptr);
last = next;
}
va_end(count);
/* uncomment next line to zero alloc'd memory */
/* memset(bptr, 0, size * last * arrsize); */
return block;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment