swap two numbers

#include <stdio.h>

//swap1由于这种方式改变不了由编译器所分配的内存地址,所以a, b的值还是不能改变,仅仅交换了副本的地址

void swap1(int *a, int *b)

{

    int *temp;

    temp = a;

    a = b;

    b = temp;

}



void swap2(int *a, int *b)

{

    int temp;

    temp = *a;

    *a = *b;
    
    *b = temp;

}

//对于swap3,不能实现交换的理由是,C语言中函数的传的是形参,也就是一个副本,虽然在函数内体内交换了,但对真实的数据没影响。

void swap3(int a, int b)

{

    int temp;

    temp = a;

    a = b;

    b = temp;



}



int main()

{

    int a = 6;

    int b = 5;

    printf("before swap\n");

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

    swap1(&a, &b);

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

    system("pause");

    return 0;

}

 

The value transfer between the actual parameter variable and the formal parameter variable in C language is a one-way "value transfer", and the value of the actual parameter pointer variable cannot be changed by executing the calling function (the pointer variable stores the address (ie pointer)), But you can change the value of the variable pointed to by the actual parameter pointer variable

 

Guess you like

Origin blog.csdn.net/qq_31702609/article/details/81292833