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;
    }
    

      

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

  • 相关阅读:
    leetcode 347. Top K Frequent Elements
    581. Shortest Unsorted Continuous Subarray
    leetcode 3. Longest Substring Without Repeating Characters
    leetcode 217. Contains Duplicate、219. Contains Duplicate II、220. Contains Duplicate、287. Find the Duplicate Number 、442. Find All Duplicates in an Array 、448. Find All Numbers Disappeared in an Array
    leetcode 461. Hamming Distance
    leetcode 19. Remove Nth Node From End of List
    leetcode 100. Same Tree、101. Symmetric Tree
    leetcode 171. Excel Sheet Column Number
    leetcode 242. Valid Anagram
    leetcode 326. Power of Three
  • 原文地址:https://www.cnblogs.com/tlsdba/p/2951534.html
Copyright © 2011-2022 走看看