Skip to content

Instantly share code, notes, and snippets.

@boki1
Created August 27, 2021 10:18
Show Gist options
  • Save boki1/c1fab45cc604b3658f8a368f9b743e7e to your computer and use it in GitHub Desktop.
Save boki1/c1fab45cc604b3658f8a368f9b743e7e to your computer and use it in GitHub Desktop.
Trying out container_of macro
#include <stdio.h>
struct inner { };
struct outer {
int a;
char b;
float c;
struct inner obj;
char asdf[];
};
#define member_type(type, member) (((type *)0)->member)
#define offsetof(type, member) ((size_t) &member_type(type, member))
#define container_of(ptr, type, member) \
({ const typeof(member_type(type, member)) *m = (ptr); \
(type *) ((char *) m - offsetof(type, member)); })
int main() {
struct outer o = { .a = 3, .b = 5, .c = 3.14 };
struct inner *inner = &o.obj;
struct outer *oo = container_of(inner, struct outer, obj);
printf("%d %d %f\n", oo->a, oo->b, oo->c);
int x = ({1; 2;}) + 3;
printf("%d\n", x);
printf("%d\n", offsetof(struct outer, c));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment