一、柔性數組(長度是0的數組)
技巧:定義在結構體最後面,佔位,用於訪問轉換之後對應位置的數據,通用用於流式數據結構化過程。例如:消息結構是16位長度,後跟數據,但數據是不定長的,代碼如下:
typedef struct
{
uint16_t len;
char data[0];
} msg_head_t;
int main()
{
uint8_t data[] = {0xa0, 0x00, 'a', 'b', 'c', '\0'};
msg_head_t* msg = (msg_head_t*)data;
cout << msg->len << endl;
cout << msg->data[0] << endl;
cout << msg->data[1] << endl;
cout << msg->data << endl;
return 0;
}
輸出:
160
a
b
abc
二、長度補整,通長用於計算最小需要對齊的緩衝區, 或加密補全,或內存映射計算地址範圍等
技巧:指令取模性能有發,位操作非常高效,先加a-1,這樣剛好時不增長,其他情況向上加1。a-1低位都是1,取反爲0,高位爲1,再與操作,則相當於去除餘數。
#define align(d, a) (((d) + (a - 1)) & ~(a - 1))
三、通過0地址,計算成員地址偏移量
#include <iostream>
using namespace std;
struct A
{
int a;
int b;
};
int main()
{
auto p = reinterpret_cast<A*>(0);
auto ptr = reinterpret_cast<long>(&(p->b)); //p-b不會異常,彙編指令實際是做地址偏移相加,未尋址
cout << ptr << endl; //輸出4
return 0;
}