Create a dynamic two-dimensional array and a dynamic two-dimensional array
1 // ============================================== ============================= 2 // create a dynamic two-dimensional array a [M] [N]; 3 // Train of Thought 1: abstract understanding of two-dimensional arrays; 4 // train of thought 2: The actual arrangement of two-dimensional arrays in memory; 5 // ============================================== =============================6 # include <stdio. h> 7 # include <stdlib. h> 8 # include <windows. h> 9 10 // The macro MIND is used to select the idea. The macro defines the compilation Idea 1, the compilation idea 2, and 11 # define MIND 1 12 13 int main () 14 {15 // m indicates the number of rows in a two-dimensional array, and n indicates the number of columns. 16 int m, n, I, j; 17 18 printf ("Enter the number of rows in a two-dimensional array :"); 19 scanf ("% d", & m); 20 printf ("Enter the number of columns in a two-dimensional array:"); 21 scanf ("% d", & n ); 22 system ("cls "); 23 24 # ifndef MIND 25 // ================================== =======================================26 // train of thought 2; 27 // =================================================== ============================= 28 printf ("Train of Thought 2 \ n "); 29 30 int * p; 31 p = (int *) calloc (m * n, sizeof (int); 32 33 // input a two-dimensional array; 34 printf ("Please input two-dimensional array elements: \ n"); 35 for (I = 0; I <m; ++ I) 36 {37 for (j = 0; j <n; ++ j) 38 {39 scanf ("% d", (p + I * n + j )); 40} 41} 42 43 // output two-dimensional array; 44 printf ("\ n two-dimensional array (row: % d column: % d): \ n "); 45 for (I = 0; I <m; ++ I) 46 {47 for (j = 0; j <n; ++ j) 48 {49 printf ("% 6d", * (p + I * n + j); 50} 51 printf ("\ n "); 52} 53 54 free (p ); 55 56 # else 57 // ====================================== =====================================58 // Train of Thought 1; 59 // ============================================ ============================= 60 printf ("Train of Thought 1 \ n "); 61 62 int ** p; 63 64 // apply for a one-dimensional dynamic pointer array; 65 p = (int **) calloc (m, sizeof (int *)); 66 67 // apply for a one-dimensional dynamic array of each row; 68 for (I = 0; I <m; ++ I) 69 {70 * (p + I) = (int *) calloc (n, sizeof (int); 71} 72 73 // enter a two-dimensional array; 74 printf ("Please input two-dimensional array elements: \ n "); 75 for (I = 0; I <m; ++ I) 76 {77 for (j = 0; j <n; ++ j) 78 {79 scanf ("% d", (* (p + I) + j); 80} 81} 82 printf ("\ n "); 83 84 // output two-dimensional array; 85 for (I = 0; I <m; ++ I) 86 {87 for (j = 0; j <n; ++ j) 88 {89 printf ("% 6d", * (p [I] + j); // the usage of the row pointer is the same here; 90} 91 printf ("\ n"); 92} 93 94 // The memory is released from the inside out; 95 for (I = 0; I <m; ++ I) 96 {97 free (* (p + I); 98} 99 free (p); 100 101 # endif102 103 system ("pause> nul"); 104 return 0; 105}