Temukan offset dalam struct [duplikat]

Oct 14 2020

Saya memiliki struct di c

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

struct Book * book;

Saya dapat mengakses book_idseperti integerbook->book_id

Tapi bagaimana saya bisa mengakses book_id dengan offset? Bagaimana saya bisa menghitung (dalam kode c) offset elemen tertentu dalam struct dan akses sepertibook+X

Jawaban

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