Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two arrays in a union in C++

is it possible to share two arrays in a union like this:

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

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

like image 603
Tobias Avatar asked Jul 09 '12 11:07

Tobias


People also ask

What is union in array in C?

A union is a special data type available in C programming language that allows to store different data types in the same memory location. Unions provide an efficient way of using the same memory location for multiple-purpose.

How do you find the intersection of a union in C?

printf("Intersection:\n"); printf("Union:\n"); for(i = 0; i < indexs; i++) printf("%d",intersection[i]); for (j = 0; j < indexu; j++) printf("%d" ,unions[j]); This code snippet prints out both "Intersection:\n" and "Union:\n" before printing array contents.


1 Answers

Both arrays are required to have the same size and layout. Of course, if you initialize anything using m_V, then all accesses to m_M are undefined behavior; a compiler might, for example, note that nothing in m_V has changed, and return an earlier value, even though you've modifed the element through m_M. I've actually used a compiler which did so, in the distant past. I would avoid accesses where the union isn't visible, say by passing a reference to m_V and a reference to m_M to the same function.

like image 77
James Kanze Avatar answered Oct 15 '22 10:10

James Kanze