zoukankan      html  css  js  c++  java
  • C语言函数实现两个数的交换、指针操作

    用函数实现数的交换

    #include<stdio.h>
    
    void swap(int x,int y)			//这个时候传递的就是值
    {
        int t;
        t = x;
        x = y;
        y = t;				//值交换
        printf("a = %d
    ",x);
        printf("b = %d
    ",y);
    }
    
    int main()
    {
        int a = 1,b = 2;
        swap(a,b);			//改变的是形参,但是实参没有改变
        printf("a = %d
    ",a);
        printf("b = %d
    ",b);
        return 0;
    }
    

    得到结果:
    在这里插入图片描述

    #include<stdio.h>
    
    void swap(int *x,int *y)			//这个时候交换的是地址
    {
        int *t;
        printf("a = %d
    ",x);
        printf("b = %d
    ",y);
        t = x;
        x = y;
        y = t;
        printf("a = %d
    ",x);
        printf("b = %d
    ",y);			//前后的地址交换了
    }
    
    int main()
    {
        int a = 1,b = 2;
        swap(&a,&b);
        printf("a = %d
    ",a);
        printf("b = %d
    ",b);
        return 0;
    }
    

    在这里插入图片描述

    #include<stdio.h>
    
    void swap(int *x,int *y)				//按指针传递
    {
        int t;
        t = *x;
        *x = *y;
        *y = t;				//此时交换的时指针指向的值
        printf("a = %d
    ",*x);
        printf("b = %d
    ",*y);
    }
    
    int main()
    {
        int a = 1,b = 2;
        swap(&a,&b);			
        printf("a = %d
    ",a);
        printf("b = %d
    ",b);
        return 0;
    }
    

    在这里插入图片描述

  • 相关阅读:
    LaTeX插入数学公式
    清除浮动的4种方式
    水平居中与垂直居中
    如何实现两三栏布局
    BFC
    flex弹性盒子
    盒模型
    Git
    jQuery设置disabled属性与移除disabled属性
    TP---where多条件查询
  • 原文地址:https://www.cnblogs.com/Indomite/p/14195252.html
Copyright © 2011-2022 走看看