C语言指针用法详解 (三) 二重指针

二重指针

例子1:

  • Question

    int **ptr1 = NULL;
    cout<<"情况一   ptr1 == "<<ptr1<<endl;
    cout<<"情况一  *ptr1 == "<<*ptr1<<endl;
    cout<<"情况一 **ptr1 == "<<**ptr1<<endl;
   /// 输出 :0  非法 非法
  • Reason:

1) 三省指针: 指针 ptr1  的类型是 int ** ,指向的类型 int*,  指定为空
2) *ptr1 是 ptr 指向的指向 ,即空的指向,非法
3) **ptr1 是 ptr 指向的指向的指向 ,即空的指向的指向,非法

例子2:

  • Question

    int * p1 = (int * )malloc(sizeof(int));
    int **ptr2 = &p1;
    cout<<"情况二   ptr2 == "<<ptr2<<endl;
    cout<<"情况二  *ptr2 == "<<*ptr2<<endl;
    cout<<"情况二 **ptr2 == "<<**ptr2<<endl;
  • Practice:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int * p1 = (int * )malloc(sizeof(int));
    int **ptr2 = &p1;
    cout<<"情况二     p1 == "<<p1<<endl;
    cout<<"情况二    *p1 == "<<*p1<<endl;
    cout<<"情况二    &p1 == "<<&p1<<endl;
    cout<<"情况二   ptr2 == "<<ptr2<<endl;
    cout<<"情况二  *ptr2 == "<<*ptr2<<endl;
    cout<<"情况二 **ptr2 == "<<**ptr2<<endl;
}

 

  • Reason:

1)三省指针:指针 p  的类型是 int * ,指向的类型 int,  初始化为没有指定其指向
2)三省指针: 指针 ptr2  的类型是 int ** ,指向的类型 int*,  指针p的地址  (注意此时 ptr2 与 &p 类型相同 都是  int** ,才可以赋值) 
3)*ptr2 是 ptr2 指向 ,即&p1的指向,为p1
4)**ptr2 是 ptr2 指向的指向 ,即*ptr2的指向,为*p1
5)指针即是地址,所以   看作 &p1 指向 p1

例子3:

  • Question

   int * p2 = (int * )malloc(sizeof(int));
    int num = 6;
    p2 = #
    int **ptr3 = &p2;
  • Practice:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int * p2 = (int * )malloc(sizeof(int));
    int num = 6;
    cout<<"情况三     p2 == "<<p2<<endl;
    p2 = #
    int **ptr3 = &p2;
    cout<<"情况三     p2 == "<<p2<<endl;
    cout<<"情况三    *p2 == "<<*p2<<endl;
    cout<<"情况三    &p2 == "<<&p2<<endl;
    cout<<"情况三   &num == "<<&num<<endl;
    cout<<"情况三   ptr3 == "<<ptr3<<endl;
    cout<<"情况三  *ptr3 == "<<*ptr3<<endl;
    cout<<"情况三 **ptr3 == "<<**ptr3<<endl;
}
 

  

  • Reason:

1)三省指针:指针 p2  的类型是 int * ,指向的类型 int,  初始化 没有指向,后指向为&num(注意此时 p2 与 &num 类型相同 都是  int* ,才可以赋值) 
2)三省指针: 指针 ptr3  的类型是 int ** ,指向的类型 int*,  指针p2的地址  (注意此时 ptr2 与 &p2 类型相同 都是  int** ,才可以赋值) 
3)*ptr3 是 ptr3 指向 ,即&p2的指向,为p2
4)**ptr3 是 ptr3 指向的指向 ,即*ptr3的指向,为*p2
5)指针即是地址,所以   看作 &num 指向 num,看作 &p2 指向 p2
 
吐吐吐吐吐吐吐槽:写博客好累啊啊啊啊啊,博客园为啥这么不好用,是我打开的方式不对吗????
原文地址:https://www.cnblogs.com/sxy-798013203/p/7639446.html