swap函數講解


交換兩個值函數swap()

剛開始學函數的時候就遇到過這個坑,突然想起就寫一寫,其實還是挺有趣的。

先講下這個函數坑的地方,上代碼

第一個坑

#include<stdio.h>
void swap(int a, int b)
{
    int temp;
    temp = a;
    a = b;
    b = temp;
}
int main()
{
    int test1 = 10, test2 = 20;
    swap1(test1, test2);
    printf("%d %d\n", test1, test2);
    return 0;
}

輸出:
10 20

會發現test1的值和test2的值並沒有交換

在函數里面改變的只是形參的值,當函數結束時,形參的生存期就結束了,其實並沒有改變實參test1和test2當中的值

第二個坑

當我們學了指針之后就會想到可以用指針修改值

#include<stdio.h>
void swap(int *a, int *b)
{
    int *temp;
    temp = a;
    a = b;
    b = temp;
}
int main()
{
    int test1 = 10, test2 = 20;
    swap1(&test1, &test2);
    printf("%d %d\n", test1, test2);
    return 0;
}

輸出:
10 20

當然還是沒有交換兩個的值,這又是為什么呢?傳入到swap函數中的是存放這兩個數的地址。但是在函數當中並沒有改變這些地址中指向的值,而是把地址交換了一遍,再把這些地址中存放的數輸出時還是和之前是一樣的

接下來就講解2種方法來寫swap函數

第一種用指針

#include<stdio.h>
void swap(int *a, int *b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}
int main()
{
    int test1 = 10, test2 = 20;
    swap(&test1, &test2);
    printf("%d %d\n", test1, test2);
    return 0;
}

輸出:
20 10

第二種用引用

#include<stdio.h>
void swap(int&a, int &b)
{
    int temp;
    temp = a;
    a = b;
    b = temp;
}
int main()
{
    int test1 = 10, test2 = 20;
    swap(test1, test2);
    printf("%d %d\n", test1, test2);
    return 0;
}

輸出:
20 10


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM