c语言中实现两个值互换的函数。
1、
#include <stdio.h> void swap(int n1, int n2) { int tmp; tmp = n1; n1 = n2; n2 = tmp; } int main(void) { int a, b; puts("please input two integers."); printf("a = "); scanf("%d", &a); printf("b = "); scanf("%d", &b); swap(a, b); //a、b作为实参传递给n1和n2,n1和n2实现了互换,但是值传递是单向的,n1和n2的值并不能返回到实参a、b中,因此a,b还是原来的值 printf("swapped a = %d\n", a); printf("swapped b = %d\n", b); return 0; }
2、将指针作为实参,可以对该指针指向的对象,也就是实参进行修改
#include <stdio.h> void swap2(int *n1, int *n2) { int tmp; tmp = *n1; *n1 = *n2; *n2 = tmp; } int main(void) { int a, b; puts("please input two integers."); printf("a = "); scanf("%d", &a); printf("b = "); scanf("%d", &b); swap2(&a, &b); //将a和b的指针作为实参传递给指针变量n1和n2,n1和n2称为指向a和b的指针,*n1和*n2分别为a和b的别名,对*n1和n2进行修改,就相当于对a和b进行修改 printf("\nswapped a = %d\n",a); printf("swapped b = %d\n", b); return 0; }