zoukankan      html  css  js  c++  java
  • 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函数。

  • 相关阅读:
    Gitlab -- 基本操作
    javascript--事件委托
    javascript--Dom 二级事件
    Tableau学习笔记之五
    Tableau学习笔记之二
    Tableau学习笔记之四
    Tableau学习笔记之三
    Tableau学习笔记之一
    Qt使用Cookies对网站操作之Get和POST
    C++ 使用Htmlcxx解析Html内容(VS编译库文件)
  • 原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/12625700.html
Copyright © 2011-2022 走看看