gpt4 book ai didi

C语言结构体访问元素

转载 作者:行者123 更新时间:2023-12-02 20:18:02 25 4
gpt4 key购买 nike

#include <stdio.h>
struct Ournode {
char x, y, z;
};

int main() {
struct Ournode p = {'1', '0', 'a' + 2};
struct Ournode *q = &p;
printf("%c, %c", *((char *)q + 1), *((char *)q + 2));
return 0;
}

我在 geeksforgeeks( https://www.geeksforgeeks.org/c-language-2-gq/input-and-output-gq/ ) 上遇到了这个问题(问题 21)。 *q 如何访问 p 的元素?如果我们有像

这样的结构怎么办?
struct Ournode {
int a,b,c;
char x, y, z;
int d;
};
int main() {
struct Ournode p = {3,4,5,'1', '0', 'a' + 2,6};
struct Ournode *q = &p;
printf("%c, %c", *((char *)q + 1), *((char *)q + 2));
printf("%d, %d\n", *((int *)q + 1), *((int *)q +2 ));
return 0;
}

在这种情况下,我们如何访问元素?有时我会得到垃圾输出,具体取决于我创建 Ournode 的顺序(即先 a,b,c 然后 x,y,z 或先 x,y,z 然后 a ,b,c)。

幕后发生了什么? q 如何访问元素?

最佳答案

How is *q accessing the elements of p?

它通过 char 指针来实现这一点,使用的规则是 struct 的地址必须与其初始元素的地址匹配(即字段 p.x)。但是,标准允许编译器在 x 之后插入填充,因此将 1 添加到 ((char*)q) 不一定会产生y 的地址。

您可以按如下方式修复您的程序:

printf(
"%c, %c"
, *((char *)q + offsetof(struct Ournode, y))
, *((char *)q + offsetof(struct Ournode, z))
);

由于 ((char*)q) 指向 int 字段 a 的一部分,因此打印 %c从这些地址产生实现定义的将 int 部分表示重新解释为 char。就打印 int 而言,您应该添加相同的 offsetof 技巧来抵消潜在填充的结果。

注意:我还没有看到编译器在 char 之间插入填充,但我没有在标准中找到任何阻止它这样做的内容。如果使用 char x[3] 代替 char x, y, z,情况会有所不同,因为数组成员之间不允许填充。

关于C语言结构体访问元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51972556/

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