gpt4 book ai didi

c - 如何从 union 内部引用 union 成员?

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:14 24 4
gpt4 key购买 nike

我正在尝试执行以下操作:

struct AlignedBuffer {
union
{
unsigned int n[4];
unsigned char b[sizeof(n)];
};
};

它的生产:

$ gcc -g3 -O1 -std=c99 -Wall -Wextra test.c -o test.exe
test.c:13:32: error: use of undeclared identifier 'n'
unsigned char b[sizeof(n)];

有没有办法从 union 内部引用 union 成员?

最佳答案

C 不允许您这样做,sizeof 的操作数必须是带括号的类型名称(n 显然不在您的示例中)或表达式(C 语法中的一元表达式), union 的成员也不是。

您可以执行以下操作之一来不对大小进行硬编码:

unsigned char b[sizeof(union { unsigned int n[4]; })];
unsigned char b[sizeof(unsigned int[4])];

在对另一个答案的评论中,您提到对齐问题是这样做的原因,因此您可能对此感兴趣:由 malloc 等分配的内存始终适合所有类型对齐。

关于c - 如何从 union 内部引用 union 成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25828835/

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