我正在处理如下结构:
struct s1 {
struct s1 *next;
char a[64];
char b[64];
struct s2 *other;
};
struct s2 {
uint32_t x;
uint32_t y;
}
获得指向 s1
的 b
的指针后,我尝试使用指针算法访问 s1->other
的成员.我尝试了以下方法:
// Assuming we have the following
struct s1 *p1 = ...
char *b = p1->b;
// Offset to get to s2
struct s2 *p2 = (struct s2*) b + 64;
// Access members
uint32_t result = p2->x;
我不认为填充是问题,因为我是从 b
开始的。
最佳答案
这一行:
struct s2 *p2 = (struct s2*) b + 64;
应该改为:
struct s2 *p2 = *(struct s2**) (b + 64);
添加括号是因为 cast 的优先级高于 +
。
使用双指针而不是常规指针,因为正如@M.M 所说,b + 64
处的对象是一个struct s2 *
(不是struct s2
)。
强制免责声明:
我假设你这样做只是为了练习。
您不应该在实际项目中使用此类技巧。如果绝对必要,至少使用 offsetof
来避免任何潜在的填充问题。
关于C 结构内存布局偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44577982/