Legit Uses of the offsetof Macro in C / C++

前端 未结 5 1679
囚心锁ツ
囚心锁ツ 2021-01-02 13:45

There is this macro offsetof in C/C++ which allows you to get the address offset of a member in a POD structure. For an example from the C FAQ:

struct foo {         


        
5条回答
  •  旧时难觅i
    2021-01-02 14:11

    Basically, anything you'd do with a pointer to member (T::*) in C++ is a good candidate for the use of offsetof in C. For that reason, offsetof is much rarer in C++.

    Now this is of course a bit circular, so here are some examples:

    • Semi-generic sorting functions for structs. qsort uses a callback, which isn't ideal. Often you just need to sort by the natural order of one member, e.g. the third int in a structure. A hypothetical qsort_int could accept an offsetof argument for this purpose.
    • Similarly, it's possible to write a macro extract such that you can say int out[10]; extract(int, &MyFoo[0], &MyFoo[10], out, offsetof(struct Foo, Bar));

提交回复
热议问题