蓝牙协议栈中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  
#include 
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的动作,空间大小的位移都是强转后的类型的大小

你可能感兴趣的:(笔记,c语言)