Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A 2D array is an 1D array of 1D arrays. As an array is simply a pointer, an array of arrays is an array of pointers. So, you use <code>malloc</code> to allocate an array of pointers (each representing a collumn), then use it again to allocate the individual arrays (each representing a row).</p> <p>To expand/shrink the array, you use <code>realloc</code><a href="http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/" rel="nofollow noreferrer">(reference)</a>. Here's an example code:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; int** alloc_matrix(int w, int h) { int** matrix; matrix = (int**) malloc(sizeof(int*) * h); for(int i = 0; i &lt; h; i++) { matrix[i] = (int*) malloc(sizeof(int) * w); } return matrix; } void realloc_matrix(int*** matrix, int new_w, int new_h) { *matrix = (int**) realloc((void *)*matrix, sizeof(int*) * new_h); for(int i = 0; i &lt; new_h; i++) { (*matrix)[i] = (int*) realloc((void *)(*matrix)[i], sizeof(int) * new_w); } } int main(int argc, char* argv[]) { // Allocating matrix int** m = alloc_matrix(10, 15); // Filling with some data for(int y = 0; y &lt; 15; y++) { for(int x = 0; x &lt; 10; x++) { m[y][x] = y * x; // Notice the index is [y][x] - NOT [x][y]! } } // Printing for(int y = 0; y &lt; 15; y++) { for(int x = 0; x &lt; 10; x++) { printf("%d\t", m[y][x]); // Notice the index is [y][x] - NOT [x][y]! } printf("\n"); } // Reallocating realloc_matrix(&amp;m, 20, 10); // Filling with some data for(int y = 0; y &lt; 10; y++) { for(int x = 0; x &lt; 20; x++) { m[y][x] = y * x; // Notice the index is [y][x] - NOT [x][y]! } } // Printing for(int y = 0; y &lt; 10; y++) { for(int x = 0; x &lt; 20; x++) { printf("%d\t", m[y][x]); // Notice the index is [y][x] - NOT [x][y]! } printf("\n"); } } </code></pre> <p>I'm sorry if I've got anything wrong. My C-fu is kinda rusty :)</p>
 

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