结构中的数组是否会出现别名/对齐问题? [英] Does Aliasing/Alignment issues occur for an Array within a Structure?

查看:41
本文介绍了结构中的数组是否会出现别名/对齐问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们在结构体中有一个数组:

If we have an array within a struct:

struct Names
{
   uint8 fileId;
   uint8 name[50];
};

然后我们尝试将数组中的 uint16 分配给 uint16 变量,例如:

and then we try to assign a uint16 from the array to a uint16 variable like:

uint16 someName = *((uint16 *)&NamesObj.name[21]);

这是否会违反别名规则/对齐规则并导致未定义的行为?

Will this violate aliasing rule/alignment rules and lead to undefined behaviour?

推荐答案

是的,这违反了 C 规则.name 中的对象是 uint8(大概是一些无符号的 8 位整数类型),它们通过一个指向 uint16(大概是一些16 位整数类型).

Yes, this violates C rules. The objects in name are uint8 (presumably some unsigned 8-bit integer type), and they are accessed through a pointer to uint16 (presumably some 16-bit integer type).

来自 N1570 草案的 2011 C 标准的相关部分是 6.5 7:

The relevant part of the 2011 C standard, from draft N1570, is 6.5 7:

对象只能通过具有以下类型之一的左值表达式访问其存储值:

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

——一种字符类型.

类型 uint16 不是这些.

这篇关于结构中的数组是否会出现别名/对齐问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆