gpt4 book ai didi

c++ - 将一些连续的数组单元读取为更大的类型是不是很麻烦?

转载 作者:行者123 更新时间:2023-12-04 17:20:58 27 4
gpt4 key购买 nike

char foo[n] = /*init here*/;  // n = 4*k + 4.
int i = 0;
while (i < n) {
int four_bytes = *reinterpret_cast<const int*>(foo + i); // is this UB?
bar(four_bytes);
i += 4;
}

在这段代码中(假设所有数据都正确初始化,并且数组的长度是 4 的倍数),这是 reinterpret_cast UB 吗?

C++14 有时是 C++11

最佳答案

对齐

char foo[n]时是UB作为 int 没有充分对齐数组。

大小1

0 < n < sizeof(int) , *reinterpret_cast<const int*>(foo + i);试图在外面引用 foo[] .


1 直到后来才看到“array's length is a multiple of 4”。然而这仍然适用于不寻常的平台,其中 sizeof int更大,比如 8。(例如,一些旧的图形处理)。 IOWs“数组的长度是 4 的倍数”未指定为与“数组的长度是 sizeof(int) 的倍数”相同

关于c++ - 将一些连续的数组单元读取为更大的类型是不是很麻烦?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66252776/

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