gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:07:07 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com