当前位置:网站首页>C language exchanges two numbers through pointers

C language exchanges two numbers through pointers

2022-07-06 18:06:00 The way of growth of Peng

#include<stdio.h>
void swap1(int *p1,int *p2){
    
	//p1,p2 They correspond to each other a,b The address of ,*p1 and *p2 They correspond to each other a and b Value  
	int p;//p It's a variable  
	p = *p1;
	*p1 = *p2;
	*p2 = p;
	// Exchange values through addresses , The actual exchange is a,b Value  
}
void swap2(int *p1,int *p2){
    
	//p1,p2 They correspond to each other c,d The address of ,*p1 and *p2 They correspond to each other c and d Value  
	// The operation of this step is to put p1 p2 These two addresses operate as formal parameters  
	int *p;//p It's a pointer  
	p = p1;
	p1 = p2;
	p2 = p;
	// This is the formal parameter exchange , And the original c d It doesn't matter. 
}

int main() {
    
	int a = 5,b = 10;
	printf(" primary a b:%d %d\n",a,b);
	swap1(&a,&b);	
	printf("swap1 after a b:%d %d\n",a,b);
	int c = 6,d = 8;
	printf(" primary c d:%d %d\n",c,d);
	swap2(&c,&b);
	printf("swap2 after c d:%d %d\n",c,d);
	return 0;
}

 Running results

原网站

版权声明
本文为[The way of growth of Peng]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060943302296.html