Is apparent NULL pointer dereference in C actually pointer arithmetic?

后端 未结 5 1399
时光取名叫无心
时光取名叫无心 2020-12-18 05:37

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

5条回答
  •  庸人自扰
    2020-12-18 06:01

    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 hi, 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 :)

提交回复
热议问题