Concise and concise + graphic function parameter passing problem (passing value, passing address 500 words to solve the battle)

1. Pass value

2. Transfer address

        Whether passing by value or by address, the formal parameter is a copy of the actual parameter

The following figure shows the exchange by passing by value:

The formal parameter left copies a new space, and the formal parameter right copies a new space

 The following figure shows the exchange by passing by pointer

The formal parameter left copies a new space, and the formal parameter right copies a new space

 

Through the above discovery, the formal parameter is a copy of the actual parameter, whether you pass it by value or by pointer.

So after knowing that the formal parameter is a copy of the actual parameter, then we must continue to explore what is stored in the copied space? ?

Value transfer: Obviously, the two values ​​of 10 and 20 are stored, and the value transfer is to copy a space, and then put the content into the new space. Perform an exchange, the function exits, the formal parameters are released, and the actual parameters remain unchanged... There is no exchange

So what about the address?

In fact, it's the same. It is also to create a space and put the content into my new space. The only difference is that this time it is not a simple data, but an address. Through this address, the data in the actual parameter can be accessed. , I can access the actual parameters, then I will get in touch with the content of the actual parameter space. Wouldn’t it be a one-step process for me to dereference, exchange and modify you?

So why do you say that the value of the actual parameter can be modified by passing the address? The reason is the above paragraph.

 perform swaps, dereference formal parameters, access data in actual parameters

The function exits, the formal parameters are released, and the modification is completed! ! !

void Swap1(int *left, int *right)
{
	cout << "形参的值:" << endl;
	cout << "left 的地址:" << left << endl;
	cout << "right 的地址:" << right << endl;
	cout << "形参的地址:" << endl;
	cout << "left 的地址:" << &left << endl;
	cout << "right 的地址:" << &right << endl;

	int *temp = left;
	*left = *right;
	right = temp;
	
}

void Swap2(int left, int right)
{
	cout << "形参的值:" << endl;
	cout << "left 的地址:" << left << endl;
	cout << "right 的地址:" << right << endl;
	cout << "形参的地址:" << endl;
	cout << "left 的地址:" << &left << endl;
	cout << "right 的地址:" << &right << endl;

	int temp = left;
	left = right;
	right = temp;

}

int main()
{
	int a = 10;
	int b = 20;
	cout << "交换前:" << endl;
	cout << "a 的实参地址为" << &a << endl;
	cout << "b 的实参地址为" << &b << endl;
	Swap2(a, b);
	cout << "交换后:" << endl;
	cout << "a = " << a << " b = " << b << endl;
	return 0;
}

 

Guess you like

Origin blog.csdn.net/weixin_66151870/article/details/129109469