Tag: offsetof

在C中明显的NULL指针取消引用实际上是指针算术吗?

我有这段代码。 它似乎在这里取消引用空指针,但随后使用unsigned int对结果进行按位与运算。 我真的不明白整个部分。 它打算做什么? 这是指针算术的一种forms吗? struct hi { long a; int b; long c; }; int main() { struct hi ob={3,4,5}; struct hi *ptr=&ob; int num= (unsigned int) & (((struct hi *)0)->b); printf(“%d”,num); printf(“%d”,*(int *)((char *)ptr + (unsigned int) & (((struct hi *)0)->b))); } 我得到的输出是44.但它是如何工作的?

编译时的偏移量

有没有办法在编译时找到结构成员的偏移量? 我希望创建一个包含结构成员偏移量的常量。 在以下代码中, 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”, […]