C语言操作

引用操作 

#include<iostream>
using namespace std;
void test1(int x){
	x = 1024;
	cout<<x<<endl;
}
void test2(int & x){
	x = 1024;
	cout<<x<<endl;
}
void swap(int & a,int & b){
	int t = a;
	a = b;
	b = t;
}
int main(){
	int x = 1;
	cout<<x<<endl;
	test2(x);//1 1024 1024 
	//test1(x); // 1 1024 1 
	cout<<x<<endl;
	int n = 10,m = 20;
	cout<<n<<' '<<m<<endl;//10 20 
	swap(n,m);
	cout<<n<<' '<<m<<endl;//20 10
	return 0;
} 
/*
什么时候要传入参数的引用“&” —— 对参数的修改结果需要“带回来”
*/
 

指针操作

#include<iostream>
using namespace std;
void swap(int* a,int* b){
	int t = *a;
	*a = *b;
	*b = t;
} 
int main(){
	int n = 10,m = 20;
	cout<<n<<' '<<m<<endl;
	swap(&n,&m);//&n 是地址 地址是int*类型 
	cout<<n<<' '<<m<<endl;
	return 0;
}
#include<stdlib.h>
    #include<stdio.h>

    void swap1(int x,int y)

    {         //当传入的是整形变量的时候,在内存中另外分配了2个变量,复制了x,y的值

    int temp;          

    temp=x;

    x=y;

    y=temp;

    }

    void swap2(int *x,int *y)

    {

    int *temp;

    temp=x;

    x=y;

    y=temp;

    }

    void swap3(int *x,int *y)

    {

    int temp;

    temp=*x;

    *x=*y;

    *y=temp;

    }

    void swap4(int a[],int b[])

    {

    int temp;

    temp=a[0];

    a[0]=b[0];

    b[0]=temp;

    }

    void swap5(int a[],int b[])

    {

    int temp;

    temp=*a;

    *a=*b;

    *b=temp;

    }

   void swap6(int *a, int *b)
   {
      if(*a  !=  *b)
      {
            *a = *a ^ *b;             //a = a ^ b ^ b;如果两个相同数疑惑,将会清0,因此要提前坐下判断
            *b = *a ^ *b;             //传统的赋值写法可适用于多种类型,其正确性也是毋庸置疑的。而异或写法除了整型之外,不 敢
            *a = *a ^ *b;             //保证其疑惑操作符在作用与浮点或自定义类型时还能正确的工作。
       }
   }

void swap7(int **x, int **y)
   {
      int *temp;
       temp=*x;    

       *x=*y;

       *y=temp;

   }
    int main()

    {

    int x,y;

    x=4;

    y=3;

   int *ppx, *ppy;

   *ppx = 4;

    *ppy = 3;

    swap1(x,y);

    printf("swap1: x:%d,y:%d\n",x,y);//形参传值,不能交换,实际传过去是拷贝的一份,没改变主函数中x,y

    swap2(&x,&y);

    printf("swap2: x:%d,y:%d\n",x,y);//不能交换,函数中只是地址交换了下,地址指向的内容没有交换

    swap3(&x,&y);

    printf("swap3: x:%d,y:%d\n",x,y);//能交换,地址指向的内容进行了交换

    swap4(&x,&y);

    printf("swap4: x:%d,y:%d\n",x,y);//能交换,地址指向的内容进行交换

    swap5(&x,&y);

    printf("swap5: x:%d,y:%d\n",x,y);//能交换,地址指向的内容进行交换

    swap6(&x,&y);

    printf("swap6: x:%d,y:%d\n",x,y);//能交换,地址指向的内容进行交换

    swap7(&ppx,&ppy);

    printf("swap7: ppx:%d,ppy:%d\n",*ppx,*ppy);//能交换,传入的是指针的地址,然后将指针的内容交换

    return 0;

    }

    swap1: x:4,y:3

    swap2: x:4,y:3

    swap3: x:3,y:4

    swap4: x:4,y:3

    swap5: x:3,y:4

    swap6: x:4,y:3

    swap7:ppx:3,ppy:4

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值