Test analysis on data exchange

Test analysis on data exchange

After being tortured by many school exam questions, I finally made up my mind to make a summary analysis of similar questions about value exchange. These include direct exchange, exchange through pointers, and exchange by reference. I attach my code below, which can more clearly reflect the inspection points of this type of question. You can research it yourself.

using namespace std;
#include<iostream>
void swap1(int *x,int *y)
{
    
    
	cout<<"before x="<<x<<endl;
	cout<<"before y="<<y<<endl;
	cout<<"before *x="<<*x<<endl;
	cout<<"before *y="<<*y<<endl;
	int *z;
	z=x;
	x=y;
	y=z;
	cout<<"after x="<<x<<endl;
	cout<<"after y="<<y<<endl;
	cout<<"after *x="<<*x<<endl;
	cout<<"after *y="<<*y<<endl;
}
void swap2(int *x,int *y)
{
    
    
	cout<<"before x="<<x<<endl;
	cout<<"before y="<<y<<endl;
	int z;
	z=*x;
	*x=*y;
	*y=z;
	cout<<"after x="<<x<<endl;
	cout<<"after y="<<y<<endl;
}
void swap3(int **x,int **y)
{
    
    
	cout<<"before x="<<*x<<endl;
	cout<<"before y="<<*y<<endl;
	int *z;
	z=*x;
	*x=*y;
	*y=z;
	cout<<"after x="<<*x<<endl;
	cout<<"after y="<<*y<<endl;
}
int main()
{
    
    
	int a=1,b=2,*pa,*pb;
	pa=&a;
	pb=&b;
	swap1(pa,pb);
	//swap2(pa,pb);
	//swap3(&pa,&pb);
	cout<<"a="<<a<<endl;
	cout<<"b="<<b<<endl;
	cout<<"pa="<<pa<<endl;
	cout<<"pb="<<pb<<endl;
	cout<<"*pa="<<*pa<<endl;
	cout<<"*pb="<<*pb<<endl;
	return 0;
}

This code defines three functions, namely swap1, swap2, and swap3. The formal parameters of the first two are first-level pointers, and the third is second-level pointers. Before the formal presentation, release two sets of codes. Readers are asked to copy the code by themselves to try whether they can complete it in their minds.
The following code is to view the address of the actual parameter when the function is called.

using namespace std;
#include<iostream>
void swap(int x,int y)
{
    
    
	cout<<"&x="<<&x<<endl;
	cout<<"&y="<<&y<<endl;
	int z;
	z=x;
	x=y;
	y=z;
	cout<<"&x="<<&x<<endl;
	cout<<"&y="<<&y<<endl;
}
int main()
{
    
    
	int a=1,b=2;
	cout<<"&a="<<&a<<endl;
	cout<<"&b="<<&b<<endl;
	swap(a,b);
	return 0;
}

The following code is an exam question of Nanjing University of Science and Technology.

using namespace std;
#include<iostream>
void f1(int *s1,int *s2)
{
    
    
	int s3=*s1;
	*s1=*s2;
	*s2=s3;
}
void f2(int *s1,int *s2)
{
    
    
	int *s3=s1;
	s1=s2;
	s2=s3;
}
void f3(int *s1,int *s2)
{
    
    
	int *p1=new int;
	int s3=*s1;
	*p1=*s2;
	*s2=s3;
}
int main()
{
    
    
	int a=1,b=2;
	int *pa=&a,*pb=&b;
	f1(pa,pb);cout<<a<<' '<<b;
	f2(pa,pb);cout<<a<<' '<<b;
	f3(pa,pb);cout<<a<<' '<<b;
	return 0;
}

The essence of this type of problem is that the pointer points to the element, and any use of replacement is futile without affecting the element itself.

Guess you like

Origin blog.csdn.net/weixin_52017909/article/details/112690108