struct A
{
uint8_t hello[3];
};
struct B
{
const struct C* hello;
};
struct C
{
uint8_t hi[3];
};
B.hello = &reinterpret_cast<C &>(A);
Assume that I have filled the structure A
with values 1
, 2
, 3
.
If I print B.hello.hi[0]
, I get 0
. Instead, I should have got 1
.
Am I doing casting wrong?
I have checked the values of struct A
right above the reinterpret_cast
line in my code and it prints ok, so I don't think I have any issue in storing the values in A
. It is just the conversion which is causing the issue.
Casts work on instances not classes, so you need to cast an instance of A not A itself
#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);
}