Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
aQuaYi opened this issue Aug 9, 2018 · 2 comments
Open

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

aQuaYi opened this issue Aug 9, 2018 · 2 comments

Comments

@aQuaYi
Copy link
Contributor

aQuaYi commented Aug 9, 2018

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
Copy link
Contributor Author

aQuaYi commented Aug 9, 2018

这是我的解答的地址 https://github.com/aQuaYi/CSAPP3E/blob/master/homework/03/3.69.md

@SydCS
Copy link

SydCS commented Nov 27, 2023

有道理

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants