开发者

Need to get the offset between a struct and one of it's fields in C

The title of the topic may as well be "Is size_t enough to hold an address?"

I'm trying to get the offset between a struct and one of it's fields and I'm using a size_t variable to hold the offset:

size_t offset = (size_t)&a开发者_JAVA技巧mp;struct.field - (size_t)&struct;

I know this is kind of forced, I'm just wondering if I might encounter somekind of error later on because of this. I know I could have done the same using an int, but I'm wondering if it can hold the address on a 64 bit system.

What are your thoughts on this?


Use the offsetof macro found in <stddef.h>.

Since size_t must have a large enough range to store the size of the largest possible object, it is also large enough to store the offset of any member of any struct type: the offset of a member of a struct cannot be greater than the size of the struct.


Use #include <stddef.h> ... offsetof(struct foo, field). It's defined to be of type size_t. size_t is not necessarily big enough to hold any address, but it's big enough to hold any offset in a struct, because it's big enough to hold sizeof(any struct).


To do this manually, you might consider doing pointer subtraction first and size_t casting second, like so:

size_t offset = (size_t)((void*)&struct.field - (void*)&struct);


As long as all items are "fixed" at compile time, you'll be safe. However, your code will be hard to maintain, and doing things this way should generally be avoided. It runs a risk of tying your code to a specific architecture as eventually one of the fields will change creating problems if all of the other calculated offsets aren't appropriately updated.

Since code tends to live longer than we think it will, the odds that some maintenance effort will eventually fix one of the values is nearly certain. Doing so would wreak havoc on the (much later) update to the field order.

I've maintained code like this. My recommendation would be to do it a different way, without the need to know exact field alignment in the code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜