C语言通过传引调用的方式交换循环顺序中的数字

要理解这个示例,您应该了解以下 C 编程 主题


通过引用传递交换元素的程序

#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

在这里,用户输入的三个数字分别存储在变量 abc 中。这些数字的地址被传递给 cyclicSwap() 函数。

cyclicSwap(&a, &b, &c);

cyclicSwap() 的函数定义中,我们将这些地址赋给了指针。

cyclicSwap(int *n1, int *n2, int *n3) {
    ...
}

cyclicSwap() 中的 n1n2n3 被更改时,main() 中的 abc 的值也会被更改。

注意: cyclicSwap() 函数不返回任何值。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战