C語言如何動態分配二維數組(轉載)
原文鏈接:https://www.cnblogs.com/0xWitch/p/9314621.html
-
使用malloc()、free()函數進行動態分配,這兩個函數包含於stdlib.h或malloc.h中
假如要申請一個3行5列的二維數組內存
1 #include <stdlib.h> 2 int main() 3 { 4 // 為二維數組分配3行 5 int **a = (int **)malloc(3 * sizeof(int *)); 6 // 為每行分配5列 7 for(int i = 0; i < 3; i++) 8 { 9 a[i] = (int *)malloc(5 * sizeof(int)); 10 } 11 return 0; 12 }
內存釋放
1 // 先釋放每列 2 for(int i = 0; i < 3; i++) 3 free(a[i]); 4 // 再釋放每行 5 free(a); 6 a = NULL; // 賦空