|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #include <stdio.h>
- typedef struct type_a
- {
- int a;
- int b;
- int c;
- char d;
- int e;
- }type_a_t;
- typedef struct type_b
- {
- int a;
- int b;
- char d;
- int e;
- }type_b_t;
- void print(type_a_t *a)
- {
- printf("a->a = %d\n", a->a);
- printf("a->b = %d\n", a->b);
- printf("a->c = %d\n", a->c);
- printf("a->d = %c\n", a->d);
- printf("a->e = %d\n", a->e);
- }
- int main()
- {
- type_b_t b;
- b.a = 1;
- b.b = 2;
- b.d = 'c';
- b.e = 72;
- print((type_a_t*)&b);
- return 0;
- }
复制代码
打印"a->e = %d\n"为什么结果是1呢?
本帖最后由 jackz007 于 2022-10-21 13:54 编辑
- #include <stdio.h>
- typedef struct type_a
- {
- int a;
- int b;
- int c;
- char d; // d 本来应该只占用 1 个字节,但是,由于后面的 e 是 int,需要在 4 字节对齐位置保存,所以,d 实际占用 4 个字节
- int e;
- }type_a_t;
- typedef struct type_b
- {
- int a;
- int b;
- char d; // d 本来应该只占用 1 个字节,但是,由于后面的 e 是 int,需要在 4 字节对齐位置保存,所以,d 实际占用 4 个字节
- int e;
- }type_b_t;
复制代码
由于代码中注释的原因,实际上,type_a 就是拥有 5 个整型数成员的结构,而 type_b 则是拥有 4 个整型数成员的结构,关于这一点,只要分别打印 sizeof(type_a) 和 sizeof(type_b) 就可以看到,type_a 比 type_b 多占用 4 个字节的内存空间。变量 b 按 type_b 进行定义和赋值,却要按 type_a 打印,那么,相当于 type_a 结构的前 4 个成员都有赋值,第 5 个成员 e 已经超出了 type_b 的结构体范围,处于未赋值的状态(也就是野值),在不同的机器上或使用不同的编译器编译,打印出的这个值(type_a 的成员 e)都不相同,比如,楼主打印的是 1,在我这里,使用 tdm-gcc 5.1.0 编译,打印出的 a -> e 的值为 3;使用 VC6.0 编译,打印出的 a -> e 是 1245120。
【tdm-gcc 5.1.0】:
- D:\[00.Exerciese.2022]\C>g++ -o x x.c
- D:\[00.Exerciese.2022]\C>x
- a->a = 1
- a->b = 2
- a->c = 99
- a->d = H
- a->e = 3
- D:\[00.Exerciese.2022]\C>
复制代码
【VC 6.0】
- D:\[00.Exerciese.2022]\C>cl x.c
- Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8804 for 80x86
- Copyright (C) Microsoft Corp 1984-1998. All rights reserved.
- x.c
- Microsoft (R) Incremental Linker Version 6.00.8447
- Copyright (C) Microsoft Corp 1992-1998. All rights reserved.
- /out:x.exe
- x.obj
- D:\[00.Exerciese.2022]\C>x
- a->a = 1
- a->b = 2
- a->c = 99
- a->d = H
- a->e = 1245120
- D:\[00.Exerciese.2022]\C>
复制代码
所以,答案就是,a -> e 是野值
|
|