Implementation method of C++ 2 d array parameter transfer

  • 2020-05-27 06:50:35
  • OfStack

C++ 2 - dimensional array parameter transfer method

int a[2][2]={ {4, 6}, {9, 11} };

I've defined an array like this, and I want to take that array as an argument, pass it into a function, and I want to be able to reference the elements of that 2-dimensional array in the function, what do I do?

The first way is to pass the 2-dimensional array directly, but you have to specify the 2-dimensional value, because if you just pass a[][], the compiler can't allocate such an array, so you pass int a[][3]

The second method is to pass the pointer array, which is int (*a)[3].

The third is passing Pointers.

See the code for specific implementation:

Method 1: pass the array. Note that the second dimension must be specified


//2 Example of a dimension array argument problem 
#include<iostream>
using namespace std;
// methods 1 : pass the array 2 Dimensions must be indicated 
void fun1(int arr[][3],int iRows)
{
 for(int i=0;i<iRows;i++)
 {
 for(int j=0;j<3;j++)
 {
  cout<<arr[i][j]<<" ";
 }
 cout<<endl;
 }
 cout<<endl;
}

Method 2:1 double pointer


void fun2(int (*arr)[3],int iRows)
{
 
 for(int i=0;i<iRows;i++)
 {
 for(int j=0;j<3;j++)
 {
  cout<<arr[i][j]<<" ";
 }
 cout<<endl;
 }
 cout<<endl;
}

Method 3: pointer passing, no matter how many dimensions of the array it is treated as a pointer,


void fun3(int*arr,int iRows,int iCols)
{
 for(int i=0;i<iRows;i++)
 {
 for(int j=0;j<3;j++)
 {
  cout<<*(arr+i*iRows+j)<<" ";
 }
 cout<<endl;
 }
 cout<<endl;
}
int main()
{
 int a[2][3]={{1,2,3},{4,5,6}};
 fun1(a,2);
 cout<<endl;
 fun2(a,2);
 cout<<endl;
 // Here you have to cast because a is 2 Dimension array, and what you need to pass in is a pointer 
 // So you have to cast to the pointer if a is 1 Dimensional arrays do not have to be cast 
 // why 1 Dimension arrays do not have to be cast 2 Dimension array must be converted, this problem has not been solved, look forward to Daniel! 
 fun3((int*)a,2,3);
 cout<<endl;
}

/*
#include<iostream>
using namespace std;
void fun(int *a,int length)
{
 int i;
 for(i=0;i<length;i++)
 {
 cout<<a[i]<<" ";
 }
 cout<<endl;
}
int main()
{
 int a[4]={1,2,3,4};
 fun(a,4);
 cout<<endl;
 return 0;
}
*/

If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, I hope to help you, thank you for your support of the site, we make progress together!


Related articles: