Trova offset nella struttura [duplicato]

Oct 14 2020

Ho struct in c

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

struct Book * book;

Posso accedere all'intero book_idcomebook->book_id

Ma come posso accedere a book_id per offset? Come posso calcolare (nel codice c) l'offset di un elemento specifico in struct e accedere comebook+X

Risposte

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)));
}