您能帮忙解释一下为什么下面的程序可以正确打印所有结构成员的值吗?
struct st
{
int i;
char c1;
int j;
char c2;
};
int main()
{
struct st a = {5, 'i', 11, 'H'};
struct st * pa = &a;
int first;
char second;
int third;
char fourth;
first = *((int*)pa);
second = *((char*)pa + 4); /* offset = 4 bytes = sizeof(int) */
third = *((int*)pa + 2); /* why (pa + 2) here? */
fourth = *((char*)pa + 12); /* why (pa + 12) here? */
printf ("first = %d, second = %c, third = %d, fourth = %c\n", first, second, third, fourth);
return 0;
}
输出:第一个 = 5,第二个 = i,第三个 = 11,第四个 = H
如何使上述程序通用化?
最佳答案
这是因为结构中添加了填充字节。 char Second;
后会添加三个填充字节,这是因为char
后面跟着一个int
(对齐较大的成员),所以填充将插入字节以使对齐方式为较大成员的对齐方式的倍数。
关于c - 使用基地址访问结构体成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52623650/