打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
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
吐吐吐吐吐吐吐槽:写博客好累啊啊啊啊啊,博客园为啥这么不好用,是我打开的方式不对吗????
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
从C语言到C++你必须学会的---动态内存和智能指针
指针作为参数传入函数的陷阱
获取WORD的高位字节和低位字节
C++动态数组
单链表的一些操作
【c++】指针参数是如何传递内存的
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服