CSAPP-3e-Solutions icon indicating copy to clipboard operation
CSAPP-3e-Solutions copied to clipboard

chapter3/3.69.md a_struct 中的 idx 可以不是 long 型。

Open aQuaYi opened this issue 7 years ago • 2 comments

3.69 B 的答案是

typedef struct {
    long idx,
    long x[4]
} a_struct

但是,实际上,根据对齐原则,idx 也可以是 int,short 和 char 类型。你可以修改以下 C 程序中设置,观察输出的结果。

#include <stdio.h>

#define CNT 7

typedef struct
{
    // 无论 idx 的类型为 char、short、int 或 long
    // 最后的 sizeof(b) 都是 0x128

    // char idx;
    // short idx;
    // int idx;
    long idx;
    long x[4];

} a_struct;

typedef struct
{
    int first;
    a_struct a[CNT];
    int last;
} b_struct;

int main(int argc, char const *argv[])
{
    a_struct a;
    b_struct b;
    printf("sizeof(a.idx) = %ld\n", sizeof(a.idx));
    printf("sizeof(a) = %ld\n", sizeof(a));
    printf("sizeof(b) = 0x%lX\n", sizeof(b));
    return 0;
}

aQuaYi avatar Aug 09 '18 06:08 aQuaYi

有道理

SydCS avatar Nov 27 '23 13:11 SydCS