结构指针指向不同的结构实例

San*_*996 5 c struct pointers

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;
}
Run Code Online (Sandbox Code Playgroud)

我得到20的输出.基本上,我试图看到,如果我声明一个结构指针,并尝试将其指向另一个结构的实例,我得到什么结果.除了来自编译器的不兼容指针类型的警告之外,它还可以构建并运行良好.我试图了解编译器如何解释此操作.不应该这是不确定的,或者可能是它,我只是对结果感到幸运.

Bre*_*ale 2

两个结构体可能具有相同的元素对齐方式:sizeof(first_struct) == sizeof(second_struct)并且:int e在结构体中以相同的偏移量开始:int b

换句话说,char d有效地存储为int布局方面的内容。这在你的平台上只是一个幸运的巧合,并且不能移植。