offsetof at compile time

前端 未结 3 1863
情歌与酒
情歌与酒 2020-12-09 13:05

Is there a way of finding the offset of a member of a structure at compile-time? I wish to create a constant containing the offset of a structure member. In the following co

3条回答
  •  一向
    一向 (楼主)
    2020-12-09 13:31

    The offsetof() macro is a compile-time construct. There is no standard-compliant way to define it, but every compiler must have some way of doing it.

    One example would be:

    #define offsetof( type, member ) ( (size_t) &( ( (type *) 0 )->member ) )
    

    While not being a compile-time construct technically (see comments by user "litb"), every compiler must have at least one such expression that it is able to resolve at compile time, which is exactly what offsetof() is defined to in .

    There is probably some other error to your code - a missing include of , or some other thing irritating your compiler.

提交回复
热议问题