简体   繁体   English

如何计算结构的偏移量

[英]How compute the offset of struct

I found a method of computing the offset of struct. 我找到了一种计算struct偏移量的方法。 as follow: 如下:

#define offsetOf(type , f)  ((int)\
 ((char *)&((struct tagName*)0)->f-(char*)(struct tagName*)0)); 

but I often write it like this: 但是我经常这样写:

#define offsetOf(type , f)  ((int)(&((struct tagName*)0)->f); 

The book said the subtraction of NULL pointer is to make sure it's correct when the inner of NULL pointer is non-zero. 该书说,NULL指针的减法是确保当NULL指针的内部非零时它是正确的。 but i think that the inner of the NULL pointer is not effect the address of the NULL Pointer. 但我认为NULL指针的内部不会影响NULL指针的地址。

为什么不使用stddef.h中定义的标准offsetof()宏?

The standard library should supply an offsetof that does exactly what you want, I would strongly recommend that you use it, as many compilers would issue a warning for the kind of code that would be required for a custom variant. 标准库应提供恰好满足您想要的功能的offsetof ,我强烈建议您使用它,因为许多编译器会针对自定义变量所需的代码种类发出警告。

Anyway, the subtract will take your code from the pointer domain to the domain of size_t . 无论如何,减法会将您的代码从指针域移到size_t域。 I would say that it's a little bit safer. 我会说这比较安全。

int should never be used to save a memory address, use uintptr_t . int永远不要用于保存内存地址,请使用uintptr_t Or just use offsetof instead of your own macro. 或者只是使用offsetof而不是您自己的宏。

0 will never be defined as something other than 0, substracting (char*)0 is just wrong. 0永远不会被定义为0以外的东西,减去(char *)0就是错误的。 What book was it that suggested this? 那是什么书暗示了这一点? Of course the addresses you deal with are just virtual addresses but your program will never see the real addresses. 当然,您处理的地址只是虚拟地址,但是您的程序将永远看不到真实地址。

The statement might make sense on some very obscure system where NULL is not 0, and you replace 0 with NULL in the macro. 该语句在NULL不为0的某些非常模糊的系统上可能有意义,并且在宏中将NULL替换为0。 Of course, if this system exists it is easy to understand why it's not known and probably a big fail. 当然,如果存在此系统,就很容易理解为什么它不为人所知,并且可能会导致很大的失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM