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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值