C/C++ 二维数组

使用C语言用到了二维数组

 1 #include <iostream>
 2 #include <stdlib.h>
 3 using namespace std;
 4 
 5 void print_arr_fun1(int arr[][3], int row){
 6     for (int i = 0; i < row; ++i){
 7         for (int j = 0; j < 3; ++j)
 8             cout << arr[i][j] << " ";
 9         cout << endl;
10     }   
11 }
12 
13 void print_arr_fun2(int *arr, int row, int col){
14     for (int i = 0; i < row; ++i){
15         for (int j = 0; j < col; ++j)
16             cout << *(arr + i * row + j) << " ";    
17         cout << endl;
18     }   
19 }
20 
21 void print_arr_fun3(int **arr, int row, int col){
22     for (int i = 0; i < row; ++i){
23         for (int j = 0; j < col; ++j)
24             cout << arr[i][j] << " ";   
25         cout << endl;
26     }   
27 }
28 
29 int main(){
30     const int row = 2;  //这里是const
31     const int col = 3;
32     int arr1[row][col];
33     for (int i = 0; i < row; ++i)
34         for (int j = 0; j < col; ++j)
35             arr1[i][j] = i * col + j;
36 
37     cout << "print_arr_fun1---------------------------" << endl;
38     print_arr_fun1(arr1, row);
39     cout << "print_arr_fun2---------------------------" << endl;
40     print_arr_fun2((int*)arr1, row, col);
41 
42     cout << "print_arr_fun3---------------------------" << endl;
43     int **arr2 = (int**)malloc(sizeof(int*) * row);
44     //malloc
45     for (int i = 0; i < row; ++i)
46         arr2[i] = (int*)malloc(sizeof(int) * col);
47     for (int i = 0; i < row; ++i)
48         for (int j = 0; j < col; ++j)
49             arr2[i][j] = i * col + j;
50     print_arr_fun3(arr2, row, col);
51 
52     //free
53     for (int i = 0; i < row; ++i)
54         free(arr2[i]);
55     free(arr2);
56 
57     return 0;
58 }

输出:

print_arr_fun1---------------------------
0 1 2 
3 4 5 
print_arr_fun2---------------------------
0 1 2 
2 3 4 
print_arr_fun3---------------------------
0 1 2 
3 4 5 

posted on 2017-10-14 18:01 旭东的博客 阅读(...) 评论(...) 编辑 收藏

导航