Two arrays in a union in C ++

Is it possible to separate two arrays in a union as follows:

struct { union { float m_V[Height * Length]; float m_M[Height] [Length]; } m_U; }; 

Do these two arrays have the same memory size or is one of them longer?

+6
source share
2 answers

Both arrays should have the same size and layout. Of course, if you initialize something with m_V , then all calls to m_M undefined behavior; the compiler may, for example, note that m_V has changed in m_V and returns an earlier value, even if you modified the element through m_M . I really used the compiler that did this in the distant past. I would avoid access when the union is not displayed, say by passing a link to m_V and a link to m_M to the same function.

+3
source

It is implicitly guaranteed that they will have the same size in memory. The compiler is not allowed to insert padding in any of the 2D array or 1D array, because everything must be compatible with sizeof .

[Of course, if you wrote to m_V and read from m_M (or vice versa), you will still be a ping of a type that technically causes undefined behavior. But that is another matter.]

+1
source

Source: https://habr.com/ru/post/920026/


All Articles