一段简单程序理解指针,大家看看有没有问题

owldestiny owldestiny 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

#include <iostream>
using namespace std;
int main()
{
//指针是一个占用内存中存储空间的变量,变量本身有地址的,是用来存储地址的,
//指针的引用即为指针中存储的地址指向的内存中存储的数据
int *p1; //声明一个指针p1,未分配指针指向的地址
cout<<"&p1: "<<&p1<<endl;//输出该指针的地址
cout<<"p1: "<<p1<<endl;//输出该指针指向的地址
//cout<<*p<<endl;//输出该指针指向的地址中存储的内容,报错,内存不能read,没有指向任何地址

int t = 2;
int *p2;//声明一个指针q,未分配指针指向的地址
p2 = &t;//指针指向t的地址
cout<<"&t: "<<&t<<endl;//输出t的地址
cout<<"p2: "<<p2<<endl;//输出指针q中存储的内容,也就是t的地址
cout<<"&p2: "<<&p2<<endl;//输出指针q的地址
cout<<"*p2: "<<*p2<<endl;//输出p2指向的地址中存储的数据,即为t

int *p3 = new int; //声明一个指针,并在指针中存储一个地址,地址不定,是程序在内存中分配的
cout<<"p3: "<<p3<<endl;//输出p3存储的地址,也就是new int 得到的地址
cout<<"&p3: "<<&p3<<endl;//输出指针p3的地址
cout<<"*p3: "<<*p3<<endl;//输出new int 得到的地址中存储的数据,不定

int *p4 = new int;//输出p4存储的地址,也就是new int 得到的地址
cout<<"p4: "<<p4<<endl;//输出p4存储的地址,也就是new int 得到的地址
cout<<"&p4: "<<&p4<<endl;//输出指针p4的地址
cout<<"*p4: "<<*p4<<endl;//输出new int 得到的地址中存储的数据,不定
p4 = &t; //将t的地址赋值给p4
cout<<"p4: "<<p4<<endl;//输出p4中存储的地址,即为t的地址
cout<<"&p4: "<<&p4<<endl;//输出p4的地址
cout<<"*p4: "<<*p4<<endl;//输出p4指向的地址中存储的内容

system("pause");
}
...全文

相关推荐

评论 20
收藏 已收藏
分享
返回顶部
owldestiny
C++ 语言 65,214 成员 250,514 内容