This is an interview question. I have no idea how to solve it. could anybody help me:?
Given a pointer to member a within a struct开发者_开发知识库ure, write a routine that returns a pointer to the structure.
Thank you!
Firstly, in order to pull that off you need to know the type of the enclosing struct StructType
and the name of the member member
. That must be a given. Without it, the problem has no solution.
Secondly, I don't know why other answers insist on reinventing the wheel (and engage into undefined and non-portable hacks on top of that) instead of using the standard offsetof
macro. With offsetof
the answer is
StructType *pstruct =
(StructType *) ((char *) pmember - offsetof(StructType, member));
The Linux kernel code (GPLv2 licensed) includes a convenient container_of()
macro:
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
It is used like this:
static inline struct ext3_inode_info *EXT3_I(struct inode *inode)
{
return container_of(inode, struct ext3_inode_info, vfs_inode);
}
@Richard's answer is excellent; the main difference is this code is parameterized to accept any struct
and any member, and as a result is correspondingly more complicated.
Given a structure named s
and a member named m
struct s * BaseS(byte *p)
{
return (struct s *) (p - ((byte*) &(((struct s *)0)->m)));
}
The idea is to get the offset of the member and subtract that from the pointer.
精彩评论