gpt4 book ai didi

从另一个结构更改一个结构的值

转载 作者:行者123 更新时间:2023-11-30 19:55:27 24 4
gpt4 key购买 nike

我刚刚读过Extending a struct in C而且我似乎不明白代码的某些部分是做什么的。
这是他当前的代码:

typedef struct A {
int x;
}A;

typedef struct B {
A a;
int d;
}B;

void fn(){
B *b;
((A*)b)->x = 10;
}

我想知道,((A*)b)->x = 10; 如何变得与 b->a.x = 10; 相同?

你如何解释这行代码?

编辑

(A*)(A*)b 做什么?

最佳答案

根据标准,指向结构的指针必须等于指向该结构的初始成员的指针。换句话说,在专用于存储struct A 内容的区域前面,不得在struct B 中插入任何填充。这就是强制转换有效的原因:

Layout of struct B

Section 6.7.2.1.13

Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning

关于从另一个结构更改一个结构的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22225422/

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