32位机器上,以下结构的sizeof(P)为

struct A {
int a;
char b;
int c;
char d;
}
struct P {
struct A w[2];
short b;
struct A* p;
}

题目链接:https://www.nowcoder.com/test/question/analytic?tid=19096674

/*考察结构体对齐和填充:
结构体每个成员相对于结构体首地址的偏移量都是成员大小的整数倍,如果不是,编译器会自动在成员间填充。*/
struct A {
int a;                            //4 bytes
char b;                        //1 bytes
//char pad[3]               //3 bytes
int c;                           //4 bytes
char d;                       //1 bytes
//char pad[3]              //3 bytes
}                            // total = 16 bytes

/* P中有结构体A的成员,但是计算时按照A中数据类型确定的*/

struct P {
struct A w[2];    // 2 * 16 bytes
short b;            //2 bytes
//char pad[2]    //2 bytes
struct A* p;      //4 bytes
}  // total = 40 bytes

可以运行程序检验一下:

迅雷校招-----第三题

相关文章: