美文网首页
【基础学习】C 指针实现数字交换

【基础学习】C 指针实现数字交换

作者: Jiubao | 来源:发表于2017-02-06 15:10 被阅读23次

通过 temp 交换 a、b 的值。

#include <stdio.h>

int a = 2;
int b = 3;

void swap(int* a, int *b)
{
    int temp = *b;
    *b = *a;
    *a = temp;
}

int main ()
{
    printf("a is %d and b is %d\n", a, b);
    
    int *pa = &a;
    int *pb = &b;
    swap(pa, pb);

    printf("a is %d and b is %d\n", a, b);
}

通过把 a、b 的指针传到 swap 方法中,实现数字的交换,因为方法是传值的,所以不能直接把 a、b 传递过去。

相关文章

网友评论

      本文标题:【基础学习】C 指针实现数字交换

      本文链接:https://www.haomeiwen.com/subject/qgquittx.html