写给朋友看 —— 一段代码理清指针难点

总而言之一句话,就是*(malloc_space + 0)和malloc_space[0]是基础的,用malloc_space的等价语句不断替换


代码

#include <stdio.h>
#include <stdlib.h>

int main()
{
   // 声明动态数组
   int *malloc_space  = (int *)malloc(sizeof(int)*3);
   *(malloc_space + 0) = 0;
   *(malloc_space + 1) = 1;
   *(malloc_space + 2) = 2;
   // 声明其它指针
   int a = 123;
   int *a_pointer = &a;
   int b = 321;
   int *b_pointer = &b;
   // 声明指针数组
   int *px[3] = { malloc_space, a_pointer, b_pointer };
	
   // 通过指针访问列表元素,*(p + 0)等价于p[0]而不是(*p)[0]
   printf("%d\n",*(malloc_space + 0));
   printf("%d\n",malloc_space[0]);
   // printf("%d\n",(*malloc_space)[0]);会报错,没有这种访问方法
   // 指针数组相关变量,px代表指针数组首地址
   printf("%d\n",px);
   // *px、px[0]是指针数组的第一个元素,即malloc_space
   printf("%d\n",malloc_space);
   printf("%d\n",*px);
   printf("%d\n",px[0]);
   // 通过指针数组访问列表元素,通过*px访问
   printf("%d\n",*(*px + 0));
   printf("%d\n",(*px)[0]);
   // 通过指针数组访问列表元素,通过px[0]访问
   printf("%d\n",*(px[0] + 0));
   printf("%d\n",px[0][0]);
	
   free(malloc_space);
   return 0;
}

运行结果

0
0
157761664
22737504
22737504
22737504
0
0
0
0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

q1uTruth

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值