Skip to content

Instantly share code, notes, and snippets.

@HQarroum
Last active August 3, 2021 21:13
Show Gist options
  • Save HQarroum/0b5d2ed623dfc145e1458230319a376f to your computer and use it in GitHub Desktop.
Save HQarroum/0b5d2ed623dfc145e1458230319a376f to your computer and use it in GitHub Desktop.
pointer-arithmetics-challenge-using-offsetof
#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