zoukankan      html  css  js  c++  java
  • 指针的引用

      复习数据结构的时候看到指针的引用,两年前学的细节确实有点想不起来,于是查了一下网上的资料,并且自己实践了一下,总结了一句话就是:指针作为参数传给函数,函数中的操作可以改变指针所指向的对象和对象的值,但函数结束后还是会指向原来的对象,若要改变,可用指针的指针或者指针的引用。

         下面是代码和截图:

      1、首先是传递指针

    #include<iostream>
    using namespace std;
    void foo(int *t,int *y);
    int main()
    {
    	int num = 4;
    	int num2 = 5;
    	int *p = #
    	int *q = &num2;
    	cout<<p<<endl;
    	cout<<q<<endl;
    	foo(p,q);
    	cout<<p<<endl;	
    	cout<<q<<endl;	
    	cout<<*p<<endl;
    	cout<<*q<<endl;
    	cin>>num;
    
    }
    void foo(int *t,int *y)
    {
    	t = y;
    	*t = 4;
    	cout<<t<<endl;
    	cout<<y<<endl;
    }
    

      q所指向的值改变,但最后p,q都还指向原来的对象

     

      2、传递指针的引用

    #include<iostream>
    using namespace std;
    void foo(int *&t,int *y);
    int main()
    {
    	int num = 4;
    	int num2 = 5;
    	int *p = #
    	int *q = &num2;
    	cout<<p<<endl;
    	cout<<q<<endl;
    	foo(p,q);
    	cout<<p<<endl;	
    	cout<<q<<endl;	
    	cout<<*p<<endl;
    	cout<<*q<<endl;
    	cin>>num;
    
    }
    void foo(int *&t,int *y)
    {
    	t = y;
    	*t = 4;
    	cout<<t<<endl;
    	cout<<y<<endl;
    }
    

      函数执行后p和q指向同一对象。 

     

      3、指针的指针

      差点被绕晕了,指针的引用还好理解,传递参数的时候直接传递指针就好,但是指针的指针就需要把那参数的几种形式理解清楚:t是传递的指针的地址,相当于foo函数中的&y,*t是指针的值,也就是所指向的对象的地址,所以我下面代码里改变他所指向的对象是用*t = y;**t就和*y表示的意思一样了,就是指向对象的值。

    #include<iostream>
    using namespace std;
    void foo(int **t,int *y);
    int main()
    {
    	int num = 4;
    	int num2 = 5;
    	int *p = #
    	int *q = &num2;
    	cout<<p<<endl;
    	cout<<q<<endl;
    	foo(&p,q);
    	cout<<p<<endl;	
    	cout<<q<<endl;	
    	cout<<*p<<endl;
    	cout<<*q<<endl;
    	cin>>num;
    
    }
    void foo(int **t,int *y)		//t是指针的地址,*t是指针的值,也就是指向的对象的地址
    {
    	*t = y;
    	cout<<*t<<endl;
    	cout<<y<<endl;
    }
    

      

      自己理解的差不多就是这样,不知道有木有什么错误的地方,望各位大虾指正~

  • 相关阅读:
    Tomcat自动部署
    java环境配置
    django-crispy-forms入门指南
    hibernate级联删除
    bzoj1659: [Usaco2006 Mar]Lights Out 关灯
    bzoj1658: [Usaco2006 Mar]Water Slides 滑水
    bzoj5470 / P4578 [FJOI2018]所罗门王的宝藏(差分约束)
    P2864 [USACO06JAN]树林The Grove
    bzoj1651 / P2859 [USACO06FEB]摊位预订Stall Reservations
    bzoj1647 / P1985 [USACO07OPEN]翻转棋
  • 原文地址:https://www.cnblogs.com/tlsdba/p/2951534.html
Copyright © 2011-2022 走看看