C: Get reference to parent struct from within nested struct
That title sound a bit confusing so here an example:
typedef struct {
int x;
int y;
} point;
typedef struct {
int width;
int height;
point topLeft;
} rectangle;
Taking this example: If you got a pointer on a point-struct 'topleft' but don't know about the struct that contains it, you can use the offsetof macro to calculate its position inside the contain (rectangle) struct an find the corresponding pointer-address to the rectangle.
#include <stddef.h>
int main() {
rectangle r = { 100, 200, { 5, 10 } };
point *p = &(r.topLeft);
rectangle *pr = (rectangle*)((char*)p - offsetof(rectangle, topLeft));
printf("r.width = %d\n", pr->width);
printf("r.height = %d\n", pr->height);
return 0;
}
Not exactly sure where and how to use it since you still have to know exactly what the containing struct is but I'm sure it will become handy somewhere.