• 双重指针


    双重指针」也有人称为「指针的指针」,其作用为「间接参照」,但无论是哪一个名词,都是令人困惑的,其实指针就是指针,所谓的多重指针,其实还是指针,它们的作用单纯来说,都是用以储存记忆体位址。 

    思考一个问题,当您要取得int变数的记忆体位址时,会使用int*来宣告指针,要取得double变数的记忆体位址时,会使用double*来宣告指针,这是因为它们在进行加减法运算时,所位移的单位并不相同,而是根据它们的资料型态而定,而如果您只是要储存一个记忆体位址,您就宣告指针为void* 型态。 

    指针可以用来储存(某变数的)记忆体位址,所以指针本身就是一个变数,也要占有记忆体空间才能储存资讯,那么指针的记忆体空间位址在哪呢?同样的使用 &运算子就可以得知了,例如:

    #include <iostream> 
    using namespace std; 

    int main() {
        int p = 10; 
        int *ptr = &p; 

        cout << "p
    的值:
    " << p 
             << endl; 
        cout << "p
    的记忆体位置
    : " << &p 
             << endl;
        cout << "*ptr
    参照的值
    : " << *ptr 
             << endl; 
     
        cout << "ptr
    储存的位址值
    : " << ptr 
             << endl; 
        cout << "ptr
    的记忆体位置
    : " << &ptr 
             << endl; 
     
        return 0; 
    }

    执行结果:

    p的值:10
    p
    的记忆体位置
    : 0x22ff74
    *ptr
    参照的值
    : 10
    ptr
    储存的位址值
    : 0x22ff74
    ptr
    的记忆体位置: 0x22ff70

     

    由以上的范例,您知道ptr在记忆体中的0x22ff70占据空间,并储存了0x22ff74这个值,0x22ff74也就是p在记忆体中的位置,该位置储存了10这个值。 

    如果在上例中,您要储存ptr的记忆体位址,也就是0x22ff70这个值,那么如何作?由于ptr是个int*型态变数,如同int变数必须宣告 int*指针,所以int*型态变数就必须宣告int**型态的指针,例如:
    int **ptr2 = &ptr;

    下面这个程式可得仔细看看:
    #include <iostream> 
    using namespace std; 

    int main() {
        int p = 10; 
        int *ptr1 = &p; 
        int **ptr2 = &ptr1; 

        cout << "p
    的值:
    " << p << endl; 
        cout << "p的记忆体位置
    : " << &p << endl; 

        cout << endl;

        cout << "*ptr1 = " << *ptr1 << endl; 
        cout << "ptr1 = " << ptr1 << endl; 
        cout << "ptr1
    的记忆体位置
    : " << &ptr1 << endl; 

        cout << endl;
     
        cout << "**ptr2 = " << **ptr2 << endl; 
        cout << "*ptr2 = " << *ptr2 << endl; 
        cout << "ptr2 = " << ptr2 << endl; 

        cout << endl;
     
        cout << "
    整理(谁储存了谁?):
    " << endl; 
        cout << "&p = " << &p << "/t/t" << "ptr1 = " << ptr1 << endl; 
        cout << "&ptr1 = " << &ptr1 << "/t" 
             << "ptr2 = " << ptr2 
             << endl;
     
        return 0; 
    }

    执行结果:

    p的值:10
    p
    的记忆体位置
    : 0x22ff74

    *ptr1 = 10
    ptr1 = 0x22ff74
    ptr1
    的记忆体位置
    : 0x22ff70

    **ptr2 = 10
    *ptr2 = 0x22ff74
    ptr2 = 0x22ff70

    整理(谁储存了谁?)

    &p = 0x22ff74           ptr1 = 0x22ff74
    &ptr1 = 0x22ff70        ptr2 = 0x22ff70

     

    在执行结果中,您可以看到最后的整理中,ptr1储存了p变数所占有的位址,而ptr2则储存了ptr1所占有的位址,所以当您使用*取值运算子时, *ptr2取出的是ptr1所储存的值,也就是&p,而再使用一次*运算子时,也就是**ptr2时,因为*ptr2 == ptr1,所以*(*ptr2 ) == *ptr1,而*ptr1 == p,所以也就是取出了p的值了。
  • 相关阅读:
    java 事务
    JPA概述以及它和Hibernate之间的关系
    [转]JavaWeb之 Servlet执行过程 与 生命周期
    j2EE的web.xml详解
    安装PyTorch 0.4.0
    [转]springmvc常用注解标签详解
    hibernate的dialect大全
    Hibernate快速入门
    DBUtils使用详解
    用户密码初始化
  • 原文地址:https://www.cnblogs.com/xiatian1071/p/3567401.html
Copyright © 2020-2023  润新知