The usage of dynamic and static two-dimensional array pointer as function parameter in C++

1. Two-dimensional static array pointer:

int arr[3][2] = {
    
    {
    
    1,2},{
    
    3,4},{
    
    5,6}};
调用函数定义方式:
int func1( int (*arr)[2],  int size ){
    
     // size表示数组的大小,应是3
	arr[1][1] = 5;...
}
int sum( int arr[][2] , int size ){
    
    ...} //2必须指定

arrIs an array name, the array has 3 elements, the first element itself is an array, composed of 2 int values. Therefore, arrthe type of is a pointer to an array of 2 ints .

2. Two-dimensional dynamic array pointer:
2.1. Do not use vector to manage memory:

int rowNum = 3;
int colNum = 2;
int **arr= new int*[rowNum]; //定义指针数组的指针(二级指针)
for(int i = 0; i < rowNum; ++i)
    ary[i] = new int[colNum];
调用函数定义方式:
void func1(int **arr,int rowNum,int coluNum){
    
    
	arr[1][0] = 1;
}
内存释放方式:
for(int i=0;i<rowNum;i++)
{
    
    
     delete[] p[i];
}
delete []p;

2.2. Use vector to manage memory:

int rowNum = 3;
int colNum = 2;
vector<vector<int>> arr(rowNum,vector<int>(colNum));
调用函数定义方式:
void func1(vector<vector<int>>& arr) {
    
    
	cout << arr[0][1] << endl;
}

Reference materials:
1. [C++] How do two-dimensional static arrays pass through pointers?
2. C++ two-dimensional dynamic array (pointer) as parameter

to sum up:

1. When using stack memory, the size of the array needs to be known in advance, and the definition of the array pointer is troublesome and inconvenient.
2. Using dynamic memory, the size of the array can be defined by variables, but the memory of the secondary pointer is difficult and requires active memory release, which is inconvenient.
3. Use vector, function to pass reference, the size of the array is variable, and memory is automatically released.

Guess you like

Origin blog.csdn.net/qq_33726635/article/details/106042079