用指针强制转换给大结构体里面的小结构体赋值的问题(字节对齐补0的影响)

#include <stdio.h>

int main(void)
{
	// 声明三个结构体
    struct B        
    {
        int a;
        int *c;
        char b;
    };
    struct C        
    {
        int a;
        int *c;
        char b;
    };
    struct A         
    {
       struct B b;
       struct C *c; 
    }p,*pp;
    
    printf("sizeof(): int: %lu, A: %lu, B: %lu C: %lu\n", sizeof(int), sizeof(struct A), sizeof(struct B), sizeof(struct C));

    int d = 2;
    printf("d: %p\n", &d);
    struct B b = {3, &d, 'a'};
    struct B *b_1 = &b;
    pp = (struct A*)(b_1);	// 给大结构体里的小结构体赋值
    
    printf("pp的数值, %d,%c,%d\n", (pp->b).a, (pp->b).b, *((pp->b).c)); // 完全正确,赋值
    printf("打印地址, %p,%p,%p\n", &((pp->b).a), ((pp->b).c), &((pp->b).b));
    
    struct C *c_1 = NULL;
    c_1 = (pp->c);
    printf("c_1: %p\n", c_1);

    if (pp && c_1) {
        printf("a:%d b:%c c:%p\n", c_1->a, c_1->b, c_1->c);     // 无效的值
        // 实际情况中这里可能做一些事,实际上不应该做
    }

    return 0;
}

输出为(64bit机器,8字节对齐,gcc):

sizeof(): int: 4, A: 32, B: 24 C: 24
d: 0x7fff217995b4
pp的数值, 3,a,2
打印地址, 0x7fff217995d0,0x7fff217995b4,0x7fff217995e0
c_1: (nil)(**被补了0,导致接下来指针为null**)
sizeof(): int: 4, A: 32, B: 24 C: 24

只更改下面部分

struct B        
{
    int a;
    char b;
    int *c;
};
..
struct B b = {3, 'a', &d};

输出

sizeof(): int: 4, A: 24, B: 16 C: 24
d: 0x7ffd866a7b44
pp的数值, 3,a,2
打印地址, 0x7ffd866a7b60,0x7ffd866a7b44,0x7ffd866a7b64
c_1: 0x7ffd866a7c60
a:1 b: c:0x7ffd866a8fda

猜你喜欢

转载自blog.csdn.net/Hu_yilang/article/details/87284595