C++ array as function parameter

Both array elements and array names can be used as parameters of functions to transfer and share data between functions.

You can use an array element as an actual parameter when calling a function, which is exactly the same as using a variable (or object) of this type as an actual parameter.

If an array name is used as a function parameter, both the actual parameter and the formal parameter should be the array name, and the type must be the same. Different from ordinary variables as parameters, when using the array name to transfer data, what is passed is the address. The first addresses of the formal parameter group and the actual parameter group coincide, and the following elements correspond to each other according to their storage order in the memory. The corresponding elements use the same data storage address, so the number of elements in the actual parameter group should not be less than that of the formal parameter group the number of elements. If the element value of the formal parameter group is changed in the called function, the corresponding element value of the real parameter group in the calling function will also be changed.

[Example] Use the array name as a function parameter. Initialize a matrix in the main function and output each element, then call the subfunction to calculate the sum of the elements of each row, store the sum directly in the first element of each row, and output the elements of each row after returning to the function of and.

void rowSum(int a[][4],int nRow)
{
    
    
	for (int i = 0; i < nRow;i++)
	{
    
    
		for (int j = 1; j < 4; j++)
		{
    
    
			a[i][0] += a[i][j];
		}
		cout << "第" << i+1 << "行元素的和为:" << a[i][0] << endl;
	}
}

int main()
{
    
    
	int arr[3][4] = {
    
     {
    
    1,2,3,4},{
    
    2,3,4,5},{
    
    3,4,5,6} };
	for (int i = 0; i < 3; i++)
	{
    
    
		for (int j = 0; j < 4; j++)
		{
    
    
			cout<<arr[i][j]<<"     ";
		}
		cout << endl;
	}
	rowSum(arr, 2);

	return 0;
}

Running results:
insert image description here
Result analysis:
Before the sub-function is called, the output values ​​of arr[i][0] are 1, 2, 3 respectively, and after the call is completed, the values ​​of arr[i][0] are 10, 14 respectively , 18, that is to say, the operation result of the formal parameter elements in the sub-function directly affects the corresponding elements of the function actual parameters.

[Note] When an array is used as a function parameter, the size of the first dimension of the array is generally not specified, and even if specified, it will be ignored.

Guess you like

Origin blog.csdn.net/NuYoaH502329/article/details/132105769