- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个使用结构建模的可变长度数据记录。给定一个内存对象,我想知道 C 标准中是否明确定义了以下内容。
我使用以下结构对问题进行建模:
struct record
{
uint32_t type;
union
{
uint8_t u8;
uint16_t u16;
uint34_t u32;
};
};
对于相关平台,
sizeof(struct record) == 8
下面的选角是否能够明确定义?
alignas(uint32_t) uint8_t buf[5];
struct record *rec = (struct record*)buffer;
通过指针访问内存对象怎么样?也就是说,访问
uint8_t x = rec->u8;
rec->u8 = x+1;
明确定义了吗?我完全预计 u16 和 u32 访问没有明确定义,可能会导致异常。
如果您能引用 c11 标准,我们将不胜感激。
感谢您的帮助。
最佳答案
关于:
alignas(uint32_t) uint8_t buf[5];
struct record *rec = (struct record*)buf;
uint8_t x = rec->u8;
(请注意,原文中的 buffer
显然是一个错误,此处已更正为 buf
。)
这违反了 C 2018 6.5 7(C 2011 有相同的文本),其中规定:
An object shall have its stored value accessed only by an lvalue expression that has one of the following types:
— a type compatible with the effective type of the object,
— a qualified version of a type compatible with the effective type of the object,
— a type that is the signed or unsigned type corresponding to the effective type of the object,
— a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
— an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
— a character type.
buf
是一个由 5 个 uint8_t
组成的数组。它是通过rec
访问的,它是一个struct record
。将此与上面列出的案例进行比较:
struct record
与 5 个 uint8_t
数组不兼容。struct record
不是与 5 uint8_t
数组兼容的类型的限定版本。struct record
不是对应于 5 个 uint8_t
数组的有符号或无符号类型。struct record
是聚合 union 类型,但其成员均不与 5 个 uint8_t
数组或上面列出的任何其他情况兼容。struct record
不是字符类型。C 标准中存在一些含糊之处或不完整。人们可能会将 rec->u8
解释为不访问 struct record
,而只是使用 struct record
来定位 u8
> 成员,然后访问它。通过这种解释,可以满足 6.5 7,因为 uint8_t 几乎肯定是字符类型,因此满足最后一种情况。 (它必须是字符类型,除非实现为其定义了扩展整数类型。)我不会依赖 C 标准的这种解释。但是,u16
和 u32
成员不会匹配任何大小写,因此使用它们肯定会违反 C 2018 6.5 7。
根据需要解释 buf
中的字节的正确方法是将它们复制到结构中:
#include <string.h> // For memcpy.
…
struct record MyRecord;
memcpy(MyRecord, buf, SomeLength);
标题询问“可变长度内存对象”,但是buf
的大小是5个字节并且不会变化。
在 alignas(uint32_t) uint8_t buf[5];
中,如果它能正常工作,alignas
最好是 alignas(struct record)
.
关于c - 通过结构体访问可变长度内存对象是否定义良好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57045349/
嗨,我正在考虑开发一种文件传输程序,想知道我是否想要尽可能好的加密,我应该使用什么? 我会用 C# 开发它,所以我可以访问 .net 库 :P在我的 usb 上有一个证书来访问服务器是没有问题的,如果
我创建的这个计算两个数组的交集是线性的方法的复杂度(在良好、平均、最差的情况下)? O(n) public void getInt(int[] a,int[] b){ int i=0; int
我已经能够使用 RTCPeerConnection.getStats() API 获得 WebRTC 音频调用的各种统计信息(抖动、RTT、丢包等)。 我需要将整体通话质量评为优秀、良好、一般或差。
基本问题: 如果我正在讲述/修改数据,我应该通过索引硬编码索引访问文件的元素,即 targetFile.getElement(5);通过硬编码标识符(内部翻译成索引),即 target.getElem
在 Linux 上,我想知道要调用什么“C”API 来获取每个 CPU 的统计信息。 我知道并且可以从我的应用程序中读取 /proc/loadavg,但这是系统范围的负载平均值,而不是每个 CPU 的
在客户端浏览器中使用 fetch api,GET 或 POST 没有问题,但 fetch 和 DELETE 有问题。它似乎将 DELETE 请求方法更改为 OPTIONS。 大多数研究表明是一个cor
我是一名优秀的程序员,十分优秀!