I found a method of computing the offset of 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. but i think that the inner of the NULL pointer is not effect the address of the NULL Pointer.
The standard library should supply an
offsetofthat 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.Anyway, the subtract will take your code from the pointer domain to the domain of
size_t. I would say that it’s a little bit safer.