struct first_struct
{
int a;
int b;
};
struct second_struct
{
char d;
int e;
};
struct second_struct second_ins = {'a',10};
struct first_struct first_ins = {20,12};
int main()
{
struct second_struct *pointer = &first_ins;
printf("%d\n",pointer->d);
return 0;
}
我得到的输出为20。基本上,我试图查看是否声明了一个结构指针,并尝试将其指向另一个结构的实例,我得到了什么结果。除了编译器警告不兼容的指针类型外,它还可以正常运行。
我试图了解编译器如何解释此操作。这不应该是不确定的,或者可能是,我只是对结果感到幸运。
最佳答案
两种结构在元素上的对齐方式都可能相同:sizeof(first_struct) == sizeof(second_struct)
和:int e
在结构中的相同偏移量开始于:int b
换句话说,就布局而言,char d
有效地存储为int
。这只是您平台上的幸运巧合,无法移植。
关于c - 指向不同结构实例的结构指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27710577/