reinterpret_cast 中的问题

Issue in reinterpret_cast

struct A
{
   uint8_t hello[3]; 
};

struct B
{
    const struct C* hello;
};

struct C
{
    uint8_t hi[3];
};

B.hello = &reinterpret_cast<C &>(A);

假设我已经用值 123 填充了结构 A。 如果我打印 B.hello.hi[0],我会得到 0。相反,我应该得到 1。 我是不是选错了?

我已经检查了代码中 reinterpret_cast 行正上方的结构 A 的值,它打印正常,所以我认为将值存储在 A。只是转换导致了问题。

转换适用于实例而不是 类,因此您需要转换 A 的实例而不是 A 本身

#include <cstdint>
#include <cassert>

struct A
{
    uint8_t hello[3];
};

struct B
{
    const struct C* hello;
};

struct C
{
    uint8_t hi[3];
};


int main()
{
    A a{}; 
    a.hello[0] = 1;
    a.hello[1] = 2;
    a.hello[2] = 3;

    B b{};
    b.hello = reinterpret_cast<C*>(&a);
    auto hi = b.hello->hi;
    assert(hi[2] == 3);
}