C/C++: Use two-dimensional array name to pass parameters

In C, when a two-dimensional array is passed as an actual parameter to a formal parameter, the parameter is automatically converted to a pointer type. At this time, if we use a two-dimensional array name to pass the parameter, we have to specify the two-dimensional array in the function parameter The length of the first dimension, otherwise it will cause a compilation error.
At this time, if you want to directly use the two-dimensional array name to pass parameters, but the two-dimensional array is dynamic, that is, the dimension of the two-dimensional array is uncertain, then we have to create a corresponding two-dimensional array for different dimension lengths The function of the formal parameter of the dimension. This is too much trouble.
In C++, we can use templates to deduce the type of a two-dimensional array (the length of the two-dimensional array can be automatically determined), so that we can directly use the two-dimensional array name to pass parameters. With the help of the template type inference function, even for two-dimensional arrays with different dimension lengths, the same function can also be used for operation.

See the code for details:

#include <iostream>

using namespace std;

template<typename T>
void print(T array, int row, int column) {
    
    
	for (int i = 0; i < row; i++) {
    
    
		for (int j = 0; j < column; j++) {
    
    
			cout << array[i][j] << ' ';
		}
		cout << endl;
	}
}

int main() {
    
    
	int a[2][2] = {
    
    {
    
    1, 2}, {
    
    3, 4}};
	int b[3][3] = {
    
    {
    
    1, 2, 3}, {
    
    4, 5, 6}, {
    
    7, 8, 9}};
	
	cout << "a = " << endl;
	print(a, 2, 2);
	cout << endl;
	cout << "b = " << endl;
	print(b, 3, 3);
	
	return 0;
}

running result:
Insert picture description here

As you can see, although the dimensions of the two-dimensional array are different, we can use the same function to operate and directly use the two-dimensional array name to pass parameters.
Using this method is still unavoidable, that is, specifying the length of each dimension of the two-dimensional array. Because when the two-dimensional array name is passed into the function as a formal parameter, the parameter becomes a pointer. At this time, with the help of sizeof, only the first dimension length of the two-dimensional array can be obtained, and the second dimension length cannot be determined, so When we use it, we must specify the length of each dimension of the two-dimensional array.
However, for different two-dimensional arrays, it is already very convenient to be able to directly use the array name to pass parameters and perform operations to the same function.

Guess you like

Origin blog.csdn.net/weixin_45711556/article/details/109232240