|
【教程】用calloc函數創建二維數組的兩種方法 |
一派掌門 二十級 |
【方法一:一次性創建全部數組空間】 #include <stdio.h> #include <stdlib.h>
int main() { // 創建二維數組 int[4][10] int i, j; int **array = (int **)calloc(4, sizeof(int *)); // 首先創建頂層指針array[][] array[0] = (int *)calloc(4, 10 * sizeof(int *)); // 這個二維數組一共有4 * 10個int型的連續空間,把這40個元素的空間直接一次性創建,然後把其中第一個元素的地址賦給指針數組array的第一個元素 /* 其實這個二維數組就是一個連續的40個int空間 和一位數組int[40]沒什麼本質區別 只不過我們又創建了指針數組int *array[4],其中這個數組的每個元素都是一個指針 第一個指針array[0]指向這個空間的第0個元素開頭 第二個指針array[1]指向這個空間的第10個元素開頭 第三個指針array[2]指向這個空間的第20個元素開頭 第四個指針array[3]指向這個空間的第30個元素開頭 這樣一來,我們就可以以為array[0] ~ [3]每個都是一個長度為10的int數組了 至於*array其實就相當於array[0] */ array[1] = array[0] + 10; // 把第10個元素的地址賦給array[1] array[2] = array[0] + 20; array[3] = array[0] + 40; // array[0] 就是我們剛才創建的空間的首地址 for (i = 0; i < 4; i++) for (j = 0; j < 10; j++) array[i][j] = (i + 1) * (j + 2); for (i = 0; i < 4; i++) { for (j = 0; j < 10; j++) printf("%d ", array[i][j]); putchar('\n'); } free(*array); // 一次性釋放全部int空間 free(array); // 釋放指針空間 return 0; } 輸出結果: 2 3 4 5 6 7 8 9 10 11 4 6 8 10 12 14 16 18 20 22 6 9 12 15 18 21 24 27 30 33 8 12 16 20 24 28 32 36 40 44
-------------------------------- Process exited after 0.006671 seconds with return value 0 Press any key to continue . . .
|
一派掌門 二十級 |
【方法2:分別創建每個第二維空間】 #include <stdio.h> #include <stdlib.h>
int main() { // 創建二維數組 int[4][10] int **array = (int **)calloc(4, sizeof(int *)); // 創建指針數組array[n] int i, j; array[0] = (int *)calloc(10, sizeof(int)); // 分別給每個指針數組創建空間並指向它 array[1] = (int *)calloc(10, sizeof(int)); array[2] = (int *)calloc(10, sizeof(int)); array[3] = (int *)calloc(10, sizeof(int)); for (i = 0; i < 4; i++) for (j = 0; j < 10; j++) array[i][j] = (i + 1) * (j + 2); for (i = 0; i < 4; i++) { for (j = 0; j < 10; j++) printf("%d ", array[i][j]); putchar('\n'); } free(array[0]); free(array[1]); free(array[2]); free(array[3]); free(array); return 0; }
|
|
一派掌門 二十級 |
【封裝成函數】 #include <stdio.h> #include <stdlib.h>
int **create2d(int row, int col) { int i; int **pp = (int **)malloc(row * sizeof(int *)); *pp = (int *)malloc(row * col * sizeof(int)); for (i = 1; i < row; i++) pp[i] = pp[i - 1] + col; return pp; }
void free2d(int **pp) { free(*pp); free(pp); }
int main() { int **a = create2d(2, 3); int i, j; a[0][0] = 10; a[0][1] = 20; a[0][2] = 30; a[1][0] = 40; a[1][1] = 50; a[1][2] = 60; for (i = 0; i < 2; i++) { for (j = 0; j < 3; j++) printf("%d ", a[i][j]); putchar('\n'); } free2d(a); return 0; }
|
|
一派掌門 二十級 |
【C++創建二維數組的簡易方法】 #include <stdio.h>
int main(void) { int (*arr)[3] = new int[2][3]; arr[0][0] = 10; arr[0][1] = 20; arr[0][2] = 30; arr[1][0] = 40; arr[1][1] = 50; arr[1][2] = 60; int *p; for (p = arr[0]; p < arr[0] + 6; p++) { printf("%d\n", *p); }
delete[] arr; return 0; }
|
|