Bluetoothプロトコルスタックのc言語ポインタノート

1719 ワード

へんちょうはいれつ

/* 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
",p_buf); printf(" malloc %x
",(uint8_t*)(p_buf+1)); printf("malloc %x
",(uint8_t*)(p_buf+1) + 3); printf("malloc %x
",p_buf->data); printf(" malloc %x
",&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
",p); printf("%x
",(char*)p); printf("%x
",(char*)(p+3)); printf("%x
",(char*)p+3); printf("%x
",p+3);

実行結果:
4e9b8b00
4e9b8b00
4e9b8b0c
4e9b8b03
4e9b8b0c


実装過程では,ポインタがどんなタイプであっても,ポインタ+nの動作にかかわらず,空間サイズの変位は強回転後のタイプの大きさであることも分かった.