使用按引用调用交换元素的程序
#include <stdio.h> void cyclicSwap(int *a, int *b, int *c); int main() { int a, b, c; printf("Enter a, b and c respectively: "); scanf("%d %d %d", &a, &b, &c); printf("Value before swapping:\n"); printf("a = %d \nb = %d \nc = %d\n", a, b, c); cyclicSwap(&a, &b, &c); printf("Value after swapping:\n"); printf("a = %d \nb = %d \nc = %d", a, b, c); return 0; } void cyclicSwap(int *n1, int *n2, int *n3) { int temp; // swapping in cyclic order temp = *n2; *n2 = *n1; *n1 = *n3; *n3 = temp; }
输出
Enter a, b and c respectively: 1 2 3 Value before swapping: a = 1 b = 2 c = 3 Value after swapping: a = 3 b = 1 c = 2
这里,用户输入的三个数字分别存储在变量
a、
b和
c中。这些数字的地址被传递给
cyclicSwap()
函数。
cyclicSwap(&a, &b, &c);
在
cyclicSwap()
的函数定义中,我们已经将这些地址分配给了指针。
cyclicSwap(int *n1, int *n2, int *n3) { ... }
当
cyclicSwap()
中的
n1、
n2和
n3发生变化时,
的值main()
中的 a、
b 和
c 也发生了变化。
注意:
cyclicSwap()
函数不返回任何内容。