#include<stdio.h>
#include<stdlib.h>
struct test{
char b;
int a;
int c ;
};
int main()
{
struct test inst;
struct test *ptr_test = &inst;
char * ptr_ch;
int* ptr_i;
/*ptr_ch = (char *) ptr_test;*/
ptr_ch = (char*)ptr_test;
ptr_i = (int *) ptr_test;
*ptr_ch = 'b';
*ptr_i = 13;
printf("char b = %c, int a = %d int c = %d", inst.b, inst.a, inst.c);
return 0;
}
我希望输出给出适当的 a、b 值和 c 的垃圾值。 但是在终端上,如果我执行 ./a.out,输出是:
, 整数 a = 134513785 整数 c = 13173540
当我做 $./a.out > tmp; vim tmp,输出为:
字符 b = ^M, int a = 134513785 int c = 12714788
问题是什么?
我想使用类型转换访问结构的各个字段。
例如,我想知道另一种返回 &(inst.a) 值的方法。
最佳答案
你的指点
ptr_ch = (char*)ptr_test;
ptr_i = (int *) ptr_test;
不要自动引用第一个适当的成员变量(在你的例子中是 b 和 a)。相反,它们只是将指向结构的指针重新解释为指向 char
或 int
的指针,因此它们指向相同的位置,即结构的地址。对于 char
,您可能很幸运,因为它是第一个成员并且您确实指向了 char
,但是您的 int
指针指向相同的地址,因此用依赖于平台和编译器的垃圾覆盖它。
所以不要做那些事情(或者当你真正知道你在做什么,更重要的是,你在哪里(在什么平台上,用什么编译器)你在做什么).
关于c - 类型转换结构以获得单独的字段地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7261281/