sizeof和offsetof会返回无符号数据,与size相减会转为无符号数,导致数组定义过大,从而编译失败。
#include <stdio.h>
#include <stddef.h>//long unsigned int
#define ASSERT_OFFSET(type, member, size) \
static inline assertOffSetOf##member(){\
char up[offsetof(type,member) - size];\
char down[size - offsetof(type,member)];\
}
#define ASSERT_STRUCT_SIZE(type, size) \
static inline assertSizeOf##type(){\
char up[sizeof(type) - size];\
char down[size - sizeof(type)];\
}
//16字节
typedef struct{
int A1;
int A2;
char res[8];//保留8字节对齐
}A;
//16字节
typedef struct{
char B1;
char B2;
char res1[2];//保留2字节对齐
int B3;
char B4;
char res2[7];
}B;
//48字节
typedef struct{
A a;
B b;
double c;
char res[8];
}BIG;
//检验偏移位置
ASSERT_OFFSET(BIG, a, 0)
ASSERT_OFFSET(BIG, b, 16)
ASSERT_OFFSET(BIG, c, 32)
//检验结构体大小
ASSERT_STRUCT_SIZE(A, 16)
ASSERT_STRUCT_SIZE(B, 16)
ASSERT_STRUCT_SIZE(BIG, 48)
int main(){
printf("offsetof(BIG,a):%lu\n", offsetof(BIG,a));
printf("offsetof(BIG,a):%lu\n", offsetof(BIG,b));
printf("offsetof(BIG,c):%lu\n", offsetof(BIG,c));
printf("==============\n");
printf("sizeof(A):%ld \nsizeof(B):%ld \nsizeof(BIG):%ld\n", sizeof(A), sizeof(B), sizeof(BIG));
return 0;
}