C结构内存布局偏移

JaJ*_*aJa 0 c memory struct

我正在处理如下结构:

struct s1 {
  struct s1 *next;
  char a[64];
  char b[64];
  struct s2 *other;
};

struct s2 {
  uint32_t x;
  uint32_t y;
}
Run Code Online (Sandbox Code Playgroud)

获得指针bs1,我正在尝试使用指针算法来访问成员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;
Run Code Online (Sandbox Code Playgroud)

我不认为填充是问题,因为我开始b.

Hol*_*Cat 5

这一行:

struct s2 *p2 = (struct s2*) b + 64;
Run Code Online (Sandbox Code Playgroud)

应改为:

struct s2 *p2 = *(struct s2**) (b + 64);
Run Code Online (Sandbox Code Playgroud)

添加了括号,因为强制转换的优先级高于+.

使用双指针而不是常规指针,因为正如@MM所说,对象at b + 64struct s2 *(不是struct s2).


强制性免责声明:

我假设你只是为了练习而做.

你不应该在实际项目中使用这些技巧.如果你绝对必须,至少offsetof要避免任何潜在的填充问题.