C 中明显的 NULL 指针取消引用实际上是指针算术吗? [英] Is apparent NULL pointer dereference in C actually pointer arithmetic?

查看:24
本文介绍了C 中明显的 NULL 指针取消引用实际上是指针算术吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码.它似乎在这里取消引用一个空指针,但随后将结果与 unsigned int 进行按位与运算.我真的不明白整个部分.它的目的是什么?这是指针算术的一种形式吗?

I've got this piece of code. It appears to dereference a null pointer here, but then bitwise-ANDs the result with unsigned int. I really don't understand the whole part. What is it intended to do? Is this a form of pointer arithmetic?

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.但它是如何工作的?

The output I get is 44. But how does it work?

推荐答案

这不是与",这是取右边参数的地址.
这是在运行时获取结构成员偏移量的标准技巧.您将 0 转换为指向 struct hi 的指针,然后引用 'b' 成员并获取其地址.然后将此偏移量添加到指针ptr"并获取ptr指向的结构的b"字段的实际地址,即ob.然后将该指针转换回 int 指针(因为 b 是 int)并输出它.这是第二次印刷.第一次打印输出num,它是4,不是因为b的值为4,而是因为4是hi结构体中b字段的偏移量.这是 sizeof(int),因为 b 跟在 a 后面,而 a 是 int...希望这是有道理的:)

This is not an "and", this is taking the address of the right hand side argument.
This is a standard hack to get the offset of a struct member at run time. You are casting 0 to a pointer to struct then referencing the 'b' member and getting its address. Then you add this offset to the pointer "ptr" and getting real address of the 'b' field of the struct pointed to by ptr, which is ob. Then you cast that pointer back to int pointer (because b is int) and output it. This is the 2nd print. The first print outputs num, which is 4 not because b's value is 4, but because 4 is the offset of the b field in hi struct. Which is sizeof(int), because b follows a, and a is int... Hope this makes sense :)

这篇关于C 中明显的 NULL 指针取消引用实际上是指针算术吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆