Created
August 27, 2021 10:18
-
-
Save boki1/c1fab45cc604b3658f8a368f9b743e7e to your computer and use it in GitHub Desktop.
Trying out container_of macro
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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