相关疑难解决方法(0)

为什么offsetof()的实现有效?

在ANSI C中,offsetof定义如下.

#define offsetof(st, m) \
    ((size_t) ( (char *)&((st *)(0))->m - (char *)0 ))
Run Code Online (Sandbox Code Playgroud)

为什么这不会引发分段错误,因为我们正在取消引用NULL指针?或者这是某种编译器黑客,它看到只有偏移的地址被取出,所以它静态地计算地址而不实际解除引用它?这个代码也可以移植吗?

c pointers offsetof

32
推荐指数
4
解决办法
2481
查看次数

&((struct name*)NULL - > b)在printf语句中

我在一本书中找到了这个代码示例,但是我无法理解printf语句中的表达式.并且这个程序成功编译输出为4.友好建议...

void main(){
    unsigned char c;

    typedef struct name {
      long a;
      int b;
      long c;
    }r;

    r re = {3,4,5};
    r *na=&re;

    printf("%d",*(int*)((char*)na + (unsigned int ) & (((struct name  *)NULL)->b)));
}
Run Code Online (Sandbox Code Playgroud)

c struct casting offsetof

9
推荐指数
1
解决办法
311
查看次数

标签 统计

c ×2

offsetof ×2

casting ×1

pointers ×1

struct ×1