Reputation: 179
Let us assume there is a struct with multiple members. The struct members are initialized with some values. The memory location of a specific member is given. Assume that you don't know the other members, their types, the ordering of members etc. Is there a way to know the memory location of the struct itself?
Is this problem called a specific name?
Upvotes: 3
Views: 201
Reputation: 66922
If you know the name of the struct, simply use offsetof
struct my_struct {
const char *name;
struct list_node list;
};
int main() {
struct my_struct t;
struct list_node* pl = &t.list;
size_t offset = offsetof(struct my_struct, list); //here
struct my_struct* pt = (struct my_struct*)((unsigned char*)pl-offset); //and here
}
If offsetof
is not viable for what you're doing, then no, there's no other way. Offsetof can alternatively be written in standard C, but there's absolutely no good reason to do that.
Upvotes: 4
Reputation: 179
Hi Everyone I found the answer this
Cast a null pointer to the struct. You can get the offset by casting the resulting address(Offset) to a char*
(char *)(&((struct *)0)->member))
You could do any type*. But char* guarantees it's always the word size.
This should be how offsetof() is written as well
Upvotes: 1
Reputation: 3622
If you know the structure type, then all you need is an offset of the field within the structure, subtract it from the member address and typecast result to pointer to the structure. For a practical implementation see FreeBSD's implementation of __containerof().
Upvotes: 2