gpt4 book ai didi

c - 重新解释适当对齐的指向具有声明类型的对象的指针

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

如果适当对齐,标准允许我们将指向对象类型的指针相互转换。 6.3.2.3(p7):

A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned68) for the referenced type, the behavior is undefined.

标准允许我们将对象表示复制到 char[sizeof(the_object_type)] 6.2.6.1(p4):

The value may be copied into an object of type unsigned char [n] (e.g., by memcpy); the resulting set of bytes is called the object representation of the value.

此外,标准明确指出

Two values (other than NaNs) with the same object representation compare equal, but values that compare equal may have different object representations.

考虑以下代码:

struct contains_64_t{
uint64_t value;
};

int main(int args, const char *argv[]){
_Alignas(struct contains_64_t)
char buf_2_64t[2 * sizeof(struct contains_64_t)];
struct contains_64_t c64_1;
c64_1.value = 1;
struct contains_64_t c64_2;
c64_2.value = 2;
memcpy(buf_2_64t, &c64_1, sizeof(c64_1));
memcpy(buf_2_64t + sizeof(c64_1), &c64_2, sizeof(c64_2));

//suitably aligned, ok
struct contains_64_t *c64_ptr = (struct contains_64_t*) buf_2_64t;
printf("Value %"PRIu64"\n", c64_ptr -> value);
}

问题:这样写代码很迂腐吗?如果不是,那么这样做可能会遇到什么样的问题?

据我所知,

我们可以将 char* 转换为 struct contains_64_t 因为它是适当对齐的。但问题是buf的声明类型是char[2 * sizeof(struct contains_64_t)]。所以正式地说,我们不能通过 struct contains_64_t * 类型的左值访问 buf

但这会很奇怪,因为我们有适当对齐的指针和完全相同的对象表示。当然,我们可以声明 struct contains_64_t buf[2];,但如果 struct 包含可变长度数组,该解决方案将不起作用

UPD:如果我们假设我们正在使用 GCC 进行编译,那么执行此类缓冲区对齐就足够了吗?

最佳答案

memcpy() 看起来不错。

c64_ptr -> value 是 UB。

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.

在标准中查找compatible以完成图片。

关于c - 重新解释适当对齐的指向具有声明类型的对象的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55252865/

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