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函数。

原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/12625700.html