Avishai Fuss
Avishai Fuss

Reputation: 73

Storing similar unions in an array in C

I have one union defined like this:

typedef union opWord
{
    struct
    {
        unsigned short ARE : 2;
        unsigned short opDest : 2;
        unsigned short opSource : 2;
        unsigned short opcode : 4;
        unsigned short group : 2;
        unsigned short unused : 3;
    } word;
    unsigned short fullReg;
} opWord;

and another very similar one only differing by bitfield arrangement:

typedef union immediate
{
    struct
    {
        unsigned short ARE : 2;
        unsigned short imm : 13;
    } word;
    unsigned short fullReg;
} immediate;

Can these be stored in the same array somehow since they only vary by the arrangement of the bits?

Something like

opWord instructions[1000]?

If not, is there a way to do it as a linked list? How would I declare pointers for that?

Upvotes: 0

Views: 66

Answers (1)

John Bollinger
John Bollinger

Reputation: 180351

You cannot directly store objects of your types opWord and immediate in the same array. You cannot declare such an array, and if you try to wrangle it with pointer casting and / or dynamically-allocated space then you run up against the strict aliasing rule.

What you can do is create a union type with an opWord and an immediate as members, and make an array of that type, as @jxh suggested in comments. In its simplest, most concise form, that might look like this:

union {
    opWord op;
    immediate imm;
} instructions[1000];

You could also consider merging your two union types into one, and creating an array of that type:

union instruction {
    struct {
        unsigned short ARE : 2;
        unsigned short opDest : 2;
        unsigned short opSource : 2;
        unsigned short opcode : 4;
        unsigned short group : 2;
        unsigned short unused : 3;
    } opWord;
    struct {
        unsigned short ARE : 2;
        unsigned short imm : 13;
    } immediate;
    unsigned short fullReg;
};

union instruction instructions[1000];

That reduces the number of layers involved, which may be useful, at the cost of losing separate types for your two kinds of instructions.

Upvotes: 2

Related Questions