C語言的swap函數的易錯點


程序一:交換值

#include <stdio.h>
void swap(int *x , int *y){
    int *temp;
    temp = x;
    x = y;
    y = temp;
}
void main(){
    int a = 1;
    int b = 2;
    swap(&a , &b);
}

對於程序一,在它運行完成之后,a,b的值並沒有發生變化。
原因是swap函數里面的x,y都是形參,函數里面對形參的地址進行了交換,這並沒有交換main函數中的a,b這兩個變量指向的地址。

程序二:交換值

#include <stdio.h>
void swap(int *x , int *y){
    int *temp;
    temp = x;
    x = y;
    y = temp;
}
void main(){
    int *a = 1;
    int *b = 2;
    swap(a , b);
}

程序二也不能交換a,b所指向的值,原因類似於程序一的錯誤原因。

程序三:交換值

#include <stdio.h>
void swap(int x , int y){
    int temp;
    temp = x;
    x = y;
    y = temp;
}
void main(){
    int a = 1;
    int b = 2;
    swap(a , b);
}

程序三運行完之后,a,b的值也沒有發生交換,是因為swap函數中的形參x,y發生了值的交換,而並不是main中實參的值交換。

程序四:交換字符串

#include <stdio.h>
void swap(char **x , char **y){
    char *temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
void main(){
    char *a = "china";
    char *b = "hello";
    swap(&a , &b);
}

程序四可以交換兩個字符串,其原理如下圖所示:

程序五:交換字符串

#include <stdio.h>
#include <string.h>
void swap(char *x , char *y){
    char temp[10];
    strcpy(temp,x);
    strcpy(x,y);
    strcpy(y,temp);
}
void main(){
    char a[10] = "china";
    char b[10] = "hello";
    swap(a , b);
}

程序五也可以交換兩個字符串,運用到了strcpy函數。


免責聲明!

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



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