C语言指针用法详解 (三) 二重指针
二重指针
例子1:
-
Question
1 2 3 4 5 | 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
1 2 3 4 5 | int * p1 = ( int * ) malloc ( sizeof ( int )); int **ptr2 = &p1; cout<< "情况二 ptr2 == " <<ptr2<<endl; cout<< "情况二 *ptr2 == " <<*ptr2<<endl; cout<< "情况二 **ptr2 == " <<**ptr2<<endl; |
-
Practice:
1 2 3 4 5 6 7 8 9 10 11 12 13 | #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
1 2 3 4 | int * p2 = ( int * ) malloc ( sizeof ( int )); int num = 6; p2 = # int **ptr3 = &p2; |
-
Practice:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #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
吐吐吐吐吐吐吐槽:写博客好累啊啊啊啊啊,博客园为啥这么不好用,是我打开的方式不对吗????
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· [翻译] 为什么 Tracebit 用 C# 开发
· 腾讯ima接入deepseek-r1,借用别人脑子用用成真了~
· Deepseek官网太卡,教你白嫖阿里云的Deepseek-R1满血版
· DeepSeek崛起:程序员“饭碗”被抢,还是职业进化新起点?
· 深度对比:PostgreSQL 和 SQL Server 在统计信息维护中的关键差异