Hacker News new | ask | show | jobs
by drran 2119 days 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.
2 comments

That 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.
But 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.