【发布时间】:2009-09-04 13:33:08
【问题描述】:
有没有办法在编译时找到结构成员的偏移量?我希望创建一个包含结构成员偏移量的常量。在下面的代码中,offsetof() 宏在第一个 printf 语句中起作用。但是,使用第 10 行声明 ofs 会产生错误:
“无法将 '->' 运算符解析为常量表达式”。
还有其他方法吗?
struct MyStruct
{
unsigned long lw;
unsigned char c[5];
int i;
int j;
unsigned long last;
};
const int ofs = offsetof(struct MyStruct, i); // This line in error
int main(void)
{
printf("Offset of c = %d.\n", offsetof(struct MyStruct, c) );
printf("Offset of i = %d.\n", ofs );
return 0;
}
【问题讨论】:
标签: c struct macros c-preprocessor offsetof