Analysis of several methods of exchanging a and b

1 Direct function exchange is unsuccessful

#include <stdio.h>


void swap(int a ,int b)
{
    
    
    printf("swap a=%d b=%d\n",a,b);
    int t = a;
    a = b;
    b =t;
    printf("swap end a=%d b=%d\n",a,b);
}


int main()
{
    
    
    int a = 1;
    int b = 10;
    swap(a,b);

    printf("a=%d b=%d\n",a,b);  

    return 0;

}

打印:
swap a=1 b=10
swap end a=10 b=1
a=1 b=10

2 Pointer exchange succeeded

#include <stdio.h>


void swap(int *a ,int *b)
{
    
    
    printf("swap a=%d b=%d\n",*a,*b);
    int t = *a;
    *a = *b;
    *b =t;
     printf("end swap a=%d b=%d\n",*a,*b);
}


int main()
{
    
    
    int a = 1;
    int b = 10;
    swap(&a,&b);

    printf("a=%d b=%d\n",a,b);  

    return 0;
}

swap a=1 b=10
end swap a=10 b=1
a=10 b=1

Guess you like

Origin blog.csdn.net/Interesting1024/article/details/109211199