1

I have struct in c

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

struct Book * book;

I can access the integer book_id like book->book_id

But how can I access to book_id by offset? How can I calc (in c code) the offset of specific element in struct and access like book+X

MicrosoctCprog
  • 460
  • 1
  • 3
  • 23
  • https://man7.org/linux/man-pages/man3/offsetof.3.html – 0___________ Oct 13 '20 at 18:56
  • First "I can access to book_id like book->book_id". No you can't, because `book` isn't a pointer. As for "access like book+X"... You can't. Not directly anyway. You can get the *byte* offset to a member, but to get a pointer to the member you need a pointer to the first *byte* of the structure. And you *must* know the exact type of each member. – Some programmer dude Oct 13 '20 at 19:01
  • 1
    And more importantly, what is the *actual* problem you're trying to solve? *Why* do you need to access the members through offsets? Right now your question is an [XY problem](http://xyproblem.info/). Please ask about the actual problem you're trying to solve instead, and add a note about this as a possible solution. We can then help you better, and possibly by giving you a better solution to the original problem. *Or* if it's just curiosity, then that's okay. But then please [edit] your question to state that. – Some programmer dude Oct 13 '20 at 19:04

1 Answers1

1
#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)));
}
0___________
  • 60,014
  • 4
  • 34
  • 74