Programming/C
[C] 동적 할당 (malloc, free)
scii
2020. 6. 11. 02:39
#include <stdio.h>
#include <malloc.h>
int main(void) {
// depth가 2, 행이 3, 열이 4인 배열을 동적 할당으로 heap 영역에 할당.
char (*data)[3][4] = (char***)malloc(sizeof(char) * 2 * 3 * 4);
for (int i = 0; i < (2 * 3 * 4); i++) {
*(*(*(data + (i / (3 * 4))) + ((i / 4)) % 3) + (i % 4)) = i;
}
for (int i = 0; i < (2 * 3 * 4); i++) {
printf("%-2d ", *(*(*(data + (i / (3 * 4))) + ((i / 4)) % 3) + (i % 4)));
if ((i % 4) == 3) {
puts("");
}
}
free(data);
return 0;
}
// 결과
/*
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
16 17 18 19
20 21 22 23
*/