在C明显的空指针引用实际指针算法? [英] Is apparent NULL pointer dereference in C actually pointer arithmetic?

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

问题描述

我已经得到这块code的。这似乎间接引用一个空指针在这里,但随后按位与运算与 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喜,则引用的是'B'成员,并获得其地址。然后,通过PTR添加此偏移到结构的'B'字段的指针PTR,并得到真正指向的地址,这就是肥胖。然后,你投这个指针回为int指针(因为b为int)和输出。
这是第2次印刷。
第一个打印输出NUM,这是4,不是因为B的值是4,但在喜结构中的B场的,因为4是偏移量。这是的sizeof(int)的,原因是b遵循,以及为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明显的空指针引用实际指针算法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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