Is there a way of finding the offset of a member of a structure at compile-time? I wish to create a constant containing the offset of a structure member. In the following code the offsetof()
macro works in the first printf
statement. However, the use in line 10 to declare ofs
generates the error:
"Cannot resolve '->' operator as a constant expression".
Is there any other way of doing it?
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.
", offsetof(struct MyStruct, c) );
printf("Offset of i = %d.
", ofs );
return 0;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…