C++指针(定义、使用、(p、p+1、*p+1)关系)、指针与数组的关系

1.指针的定义 2.指针的使用

如下代码:

//1.指针的定义
int a = 10;
int* p;
p = &a;//实际上是让p指向a的地址
//上面两行等价于
int* p=&a;
cout << "a的地址(&a):" << (int) & a << endl;
cout << "a的地址(p):" << (int)p << endl;

//2.指针的使用
//可以通过解引用的方式来找到指针指向的内存
//指针前面加“*”,代表解引用,找到指针指向的内存中的数据
cout << "*p=" << *p << endl;
*p = 100;//通过修改指针指向内存中的数据,修改a的值。
cout << "*p=" << *p << endl;
cout << "a=" << a << endl;

运行结果:
在这里插入图片描述

3.指针所占内存空间

int a = 10;
int* p=&a;
//查看指针所占内存空间的大小
cout << "sizeof(int *):" << sizeof(int *) << endl;
cout << "sizeof(p):" << sizeof(p) << endl;//与上面等价
cout << "sizeof(*p):" << sizeof(*p) << endl;//实际上是查看int所占内存空间大小
cout << "sizeof(char *):" << sizeof(char *) << endl;
cout << "sizeof(float *):" << sizeof(float *) << endl;
cout << "sizeof(double *):" << sizeof(double *) << endl;
cout << "sizeof(string *):" << sizeof(string *) << endl;

运行结果:
64位操作系统(x64)
在这里插入图片描述
32位操作系统(x84)
在这里插入图片描述

原因:指针所占内存空间大小与操作系统有关,32位4,64位为8.
其中sizeof(*p),实际上是int所占内存大小。

4.p、p+1、*p+1、※(p+1)关系

	int a[3] = { 1,5,10 };
	int* p = a;
	cout << "a[0]的地址、p的地址:p:" << (int)p << endl;
	cout << "*p=a[0]=" << *p << endl;
	cout << "p[1]=*(p+1)=*(a+1)=a[1]=" << *(p + 1) << endl;
	cout << "*p+1=p[0]+1=*a+1=a[0]+1=" << *p + 1 << endl;
	cout << "a[1]的地址:p+1=&a[1]=a+1=" << (int)(p + 1) << endl;
	cout << "p[1]=" << p[1] << endl;

运行结果:

在这里插入图片描述

5.p、p+1、*p+1与数组对比

https://blog.csdn.net/weixin_44190648/article/details/121889017

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值