蓝牙协议栈中c语言指针笔记

变长数组

/* Define the header of each buffer used in the Bluetooth stack.
 */
typedef struct {
  uint16_t event;
  uint16_t len;
  uint16_t offset;
  uint16_t layer_specific;
  uint8_t data[];
} BT_HDR;

BT_HDR* p_buf = (BT_HDR*)osi_malloc(A2DP_SBC_BUFFER_SIZE);
uint8_t* output = (uint8_t*)(p_buf + 1) + p_buf->offset + p_buf->len;

这个output最后指向哪里了呢?

做了实验:

#include  <stdio.h>
#include <malloc.h>
typedef unsigned int uint16_t;
typedef unsigned char uint8_t;

typedef struct {
  uint16_t event;
  uint16_t len;
  uint16_t offset;
  uint16_t layer_specific;
  uint8_t data[];
} BT_HDR;
int main(void)
{
BT_HDR* p_buf = (BT_HDR*)malloc(4096+16);
printf(" malloc %x\n",p_buf);
printf(" malloc %x\n",(uint8_t*)(p_buf+1));
printf("malloc %x\n",(uint8_t*)(p_buf+1) + 3);
printf("malloc %x\n",p_buf->data);
printf(" malloc %x\n",&p_buf->data[3]);
}

执行结果:

malloc 194b010
malloc 194b020
malloc 194b023
 malloc 194b020
malloc 194b023


这种情况下,p_buf+1就指向了data变长数组所指向的malloc空间了

因此output最后指向p_buf ->data[p_buf->offset + p_buf->len]空间

指针强转位移

int *p = NULL;
int  c[12] = {1};
for ( j = 0;j<12;j++)
{
	c[j] = j;
}
p =  c;
printf(" %x\n",p);
printf("%x\n",(char*)p);
printf("%x\n",(char*)(p+3));
printf("%x\n",(char*)p+3);
printf("%x\n",p+3);

执行结果:

4e9b8b00
4e9b8b00
4e9b8b0c
4e9b8b03
4e9b8b0c

实现过程 还发现,
不管指针什么类型,指针+n的动作,空间大小的位移都是强转后的类型的大小

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值