3 ms·
Negative offset is used often to access fields in parent struct having pointer to a field only. For example, to implement garbage collection or string type.
by drran 6y ago
Negative offset is used often to access fields in parent struct having pointer to a field only. For example, to implement garbage collection or string type.
- wahern 6y agoBut p - 2 is not the same as p + -2, and it's not clear in your example whether the former suffices or the latter is required. I can definitely imagine examples where the latter is required--certainly C clearly accommodates this usage--but IME it's nonetheless a rare scenario and not something that could, alone, justify always using signed offsets. Pointers are intrinsically neither signed nor unsigned; it's how you use them that matters.
- a1369209993 6y agoThat should be: Parent* p = container_of(field,Parent,pa_somefield); access(p->pa_otherfield); You'd usually define container_of using subtraction (not negative offset per se): #define container_of(FIELD,TYPE,MEMB) ({ \ const typeof( ((TYPE*)0)->MEMB )* _mptr = (FIELD); \ (TYPE*)( (char*)_mptr - __builtin_offsetof(TYPE,MEMB) ); \ }) but you shouldn't actually be using that directly, because thats what the macro is for.