C語言動態分配二維數組


1 #include <iostream>
 2
 3 using namespace std;
 4
 5 void display_array(int** p_arr, int width, int height)
 6 {
 7     for (int i = 0; i < width; i ++)
 8     {
 9         for (int j = 0; j < height; j ++)
10         {
11             cout << p_arr[i][j] << " ";
12         }
13         cout << endl;
14     }
15 }
16 void free_array(int** p_arr, int width, int height)
17 {
18     for (int i = 0; i < width; i ++)
19     {
20         free(p_arr[i]);
21     }
22     free(p_arr);
23 }
24
25 int main(int argc, char* argv[])
26 {
27     int cnt = 10;
28     int** p_array = NULL;
29     cout << "input array size: m n: " << endl;
30     int m, n;
31     cin >> m >> n;
32     p_array = (int**)malloc(m*sizeof(int*));
33     for (int i = 0; i < m; i ++)
34     {
35         p_array[i] = (int*)malloc(n*sizeof(int));
36         for (int j = 0; j < n; j ++)
37         {
38             p_array[i][j] = cnt;
39             cnt ++;
40         }
41     }
42     display_array(p_array, m, n);
43     free_array(p_array, m, n);
44     return 0;
45 }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章