Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your organization of the allocations is a bit odd. If you have 3 dimensions (lets call them levels, rows, and columns), you would normally allocate space to hold the levels, and then for each level you would allocate the space for the rows within the level, and then finally you would allocate the space for the columns within the row.</p> <p>Your code seems to start in the middle (rows); then does some work at levels; and finally at the columns.</p> <p>This code is a complete rewrite of yours, but it works without crashing. I've not yet validated it with <code>valgrind</code>; I need to upgrade the version on this machine.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #define ZALLOC(item, n, type) if ((item = (type *)calloc((n), sizeof(type))) == NULL) \ fatalx("Unable to allocate %d unit(s) for item\n", n) static void fatalx(const char *str, size_t n) { fprintf(stderr, "%s: %zu\n", str, n); exit(1); } static int ***alloc_3d(int levels, int rows, int cols) { int count = 0; int ***array_3d; ZALLOC(array_3d, levels, int **); for (int i = 0; i &lt; levels; i++) { int **data; ZALLOC(data, rows, int *); array_3d[i] = data; for (int j = 0; j &lt; rows; j++) { int *entries; ZALLOC(entries, cols, int); array_3d[i][j] = entries; for (int k = 0; k &lt; cols; k++) { array_3d[i][j][k] = count++; } } } return array_3d; } static void print_3d(int ***a3d, int levels, int rows, int cols) { for (int i = 0; i &lt; levels; i++) { printf("%d:\n", i); for (int j = 0; j &lt; rows; j++) { printf(" %d: ", j); for (int k = 0; k &lt; cols; k++) printf(" %3d", a3d[i][j][k]); putchar('\n'); } } } static void free_3d(int ***a3d, int levels, int rows) { for (int i = 0; i &lt; levels; i++) { for (int j = 0; j &lt; rows; j++) free(a3d[i][j]); free(a3d[i]); } free(a3d); } int main(void) { int d1 = 3; int d2 = 5; int d3 = 7; int ***a3d = alloc_3d(d1, d2, d3); print_3d(a3d, d1, d2, d3); free_3d(a3d, d1, d2); return(0); } </code></pre> <p>Output:</p> <pre><code>0: 0: 0 1 2 3 4 5 6 1: 7 8 9 10 11 12 13 2: 14 15 16 17 18 19 20 3: 21 22 23 24 25 26 27 4: 28 29 30 31 32 33 34 1: 0: 35 36 37 38 39 40 41 1: 42 43 44 45 46 47 48 2: 49 50 51 52 53 54 55 3: 56 57 58 59 60 61 62 4: 63 64 65 66 67 68 69 2: 0: 70 71 72 73 74 75 76 1: 77 78 79 80 81 82 83 2: 84 85 86 87 88 89 90 3: 91 92 93 94 95 96 97 4: 98 99 100 101 102 103 104 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload