Skip to content

Instantly share code, notes, and snippets.

@zapstar
Created December 8, 2016 14:15
Show Gist options
  • Save zapstar/8e465c9a25082a6c02fcb086e4105969 to your computer and use it in GitHub Desktop.
Save zapstar/8e465c9a25082a6c02fcb086e4105969 to your computer and use it in GitHub Desktop.
Get the outer structure's pointer from the inner structure in C.
#include <stddef.h>
typedef struct inner {
int i_a;
int i_b;
int i_c;
} inner_t;
typedef struct outer {
int o_a;
int o_b;
int o_c;
inner_t o_inner;
} outer_t;
// MACRO to find the address of the outer structure
// t -> the type of the outer structure
// f -> the inner structure's field name in outer structure
// p -> pointer to the inner structure in outer structure
#define GET_PARENT(t, f, p) ((t *) ((char *) p - offsetof(t, f)))
// Example usage
void foo_function(inner_t *iptr)
{
printf("%p\n", GET_PARENT(outer_t, o_inner, iptr));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment