c++ — 二维数组参数传递

都知道,数组名和函数名一样,可以当做指针(普通指针和函数指针)来用。

关于二维数组做为形参声明和实参传递,直接看代码:

1 #include <iostream>
 2 using namespace std;
 3 
 4 /*传二维数组*/
 5 
 6 //第1种方式:传数组,第二维必须标明
 7 /*void display(int arr[][4])*/
 8 void display1(int arr[][4],const int irows)
 9 {
10     for (int i=0;i<irows;++i)
11     {
12         for(int j=0;j<4;++j)
13         {
14             cout<<arr[i][j]<<" ";     //可以采用parr[i][j]
15         }
16         cout<<endl;
17     }
18     cout<<endl;
19 }
20 
21 //第2种方式:一重指针,传数组指针,第二维必须标明
22 /*void display(int (*parr)[4])*/
23 void display2(int (*parr)[4],const int irows)
24 {
25     for (int i=0;i<irows;++i)
26     {
27         for(int j=0;j<4;++j)
28         {
29             cout<<parr[i][j]<<" ";    //可以采用parr[i][j]
30         }
31         cout<<endl;
32     }
33     cout<<endl;
34 }
35 //注意:parr[i]等价于*(parr+i),一维数组和二维数组都适用
36 
37 //第3种方式:传指针,不管是几维数组都把他看成是指针
38 /*void display3(int *arr)*/
39 void display3(int *arr,const int irows,const int icols)
40 {
41     for(int i=0;i<irows;++i)
42     {
43         for(int j=0;j<icols;++j)
44         {
45             cout<<*(arr+i*icols+j)<<" ";   //注意:(arr+i*icols+j),不是(arr+i*irows+j)
46         }
47         cout<<endl;
48     }
49     cout<<endl;
50 }
51 
52 /***************************************************************************/
53 /*
54 //第2种方式:一重指针,传数组指针void display(int (*parr)[4])
55 //缺陷:需要指出第二维大小
56 typedef int parr[4];
57 void display(parr *p)
58 {
59     int *q=*p;        //q指向arr的首元素
60     cout<<*q<<endl;   //输出0
61 }
62 
63 typedef int (*parr1)[4];
64 void display1(parr1 p)
65 {
66     cout<<(*p)[1]<<endl;  //输出1
67     cout<<*p[1]<<endl;    //输出4,[]运算符优先级高
68 }
69 //第3种方式:
70 void display2(int **p)
71 {
72     cout<<*p<<endl;           //输出0
73     cout<<*((int*)p+1+1)<<endl; //输出2
74 }
75 */
76 
77 int main()
78 {
79     int arr[][4]={0,1,2,3,4,5,6,7,8,9,10,11};
80     int irows=3;
81     int icols=4;
82     display1(arr,irows);
83     display2(arr,irows);
84 
85     //注意(int*)强制转换.个人理解:相当于将a拉成了一维数组处理。
86     display3((int*)arr,irows,icols);
87     return 0;
88 }

推荐使用第2种方式,简单明了!
原文链接: https://www.cnblogs.com/cygalaxy/p/6963789.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/254981

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 上午8:25
下一篇 2023年2月14日 上午8:28

相关推荐