Last active
July 3, 2024 21:27
-
-
Save HQarroum/0b5d2ed623dfc145e1458230319a376f to your computer and use it in GitHub Desktop.
pointer-arithmetics-challenge-using-offsetof
This file contains 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> | |
#include <stddef.h> | |
/** | |
* An example structure that holds members of different | |
* types and sizes that we will be using in our example. | |
*/ | |
typedef struct { | |
float f; | |
int member; | |
char c; | |
} t_struct; | |
/** | |
* A function returning a pointer to a structure of type `t_struct` | |
* given a pointer to one of its member. | |
*/ | |
t_struct* get_struct_ptr(void* member_ptr) { | |
return (t_struct*)((char*) member_ptr - offsetof(t_struct, member)); | |
} | |
int main(void) { | |
t_struct test; | |
t_struct* ptr; | |
ptr = get_struct_ptr(&test.member); | |
if (ptr == &test) { | |
printf("It works !\n"); | |
} | |
return (0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment