Rechercher le décalage dans la structure [duplicate]

Oct 14 2020

J'ai struct en c

struct Book {
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
};

struct Book * book;

Je peux accéder à l'entier book_idcommebook->book_id

Mais comment puis-je accéder à book_id par offset? Comment puis-je calculer (en code c) le décalage d'un élément spécifique dans struct et accéder commebook+X

Réponses

1 P__JsupportswomeninPoland Oct 14 2020 at 02:07
#define offset(type, member)  ((size_t)&(((type *)0) -> member))
#define ACCESS(object, type, offset)  (type *)(((char *)&(object)) + (offset))

typedef struct
{
    int a,b,c;
}t;

int main(void)
{
    t s = {1,2,3};
    printf("%zu\n", offset(t,b));
    printf("%d\n", *ACCESS(s, int, offset(t,b)));
}