0
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.

Evg
  • 25,259
  • 5
  • 41
  • 83
varconst
  • 15
  • 6
  • 2
    *Instead, I should have got 1* - Why? Take a look at the [list of valid conversions](https://en.cppreference.com/w/cpp/language/reinterpret_cast) that `reinterpret_cast` can do and think which bullet applies to what you're trying to do. – Evg Aug 26 '21 at 07:51

1 Answers1

2

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);
}
Pepijn Kramer
  • 9,356
  • 2
  • 8
  • 19
  • 3
    This is sheer undefined behaviour. [What is the strict aliasing rule?](https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule) – Evg Aug 26 '21 at 07:47
  • I agree it is undefine. It is not something I would do either, but the question was about the cast. Not if it was smart to wite code like this (which it isn't). ;) – Pepijn Kramer Aug 26 '21 at 09:11