gpt4 book ai didi

c - 仅给出成员位置时结构的位置

转载 作者:太空狗 更新时间:2023-10-29 16:01:42 28 4
gpt4 key购买 nike

让我们假设有一个包含多个成员的结构。结构成员用一些值初始化。给出了特定成员的内存位置。假设您不知道其他成员、他们的类型、成员的顺序等。有没有办法知道结构本身的内存位置?

这个问题有具体的名字吗?

最佳答案

如果您知道结构的名称,只需使用 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
}

如果 offsetof 对于您正在做的事情不可行,那么不,没有其他方法。 Offsetof 也可以用标准 C 编写,但绝对没有充分的理由这样做。

关于c - 仅给出成员位置时结构的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23771582/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com