bobby
bobby

Reputation: 2789

Initialise a structure containing a union

I have some code as follows

typedef struct _DisplayString
{
    char* string;
}DisplayString;

typedef struct _DisplayGroup
{
    char groupName[10];
    int groupType;
}DisplayGroup;

typedef struct _Info {
    int x;
    union display
    {
        DisplayString displayString;
        DisplayGroup  displayGroup;
    }Display;
}Info;


int main(void) {

    DisplayString stringType;
    DisplayGroup groupType;
    Info infoField = { 0, {stringType}};
    Info groupFields = { 0, {groupType}};
    return 0;
}  

I am trying to initialise the structure fields. I am getting a compiler error on the line initialising the groupFields data variable

gcc -Wall -g settings.c 
settings.c: In function ‘main’:
settings.c:29:5: warning: missing braces around initializer [-Wmissing-braces]
settings.c:29:5: warning: (near initialization for ‘groupFields.Display.displayString’) [-Wmissing-braces]
settings.c:29:5: error: incompatible types when initializing type ‘char *’ using type ‘DisplayGroup’
settings.c:29:10: warning: unused variable ‘groupFields’ [-Wunused-variable]
settings.c:28:10: warning: unused variable ‘infoField’ [-Wunused-variable]

Why does this happen?

Upvotes: 1

Views: 235

Answers (3)

Long_GM
Long_GM

Reputation: 191

I think you should declare the display union as:

union display
{
    DisplayString displayString;
    DisplayGroup  displayGroup;
};

Or:

typedef union display
{
    DisplayString displayString;
    DisplayGroup  displayGroup;
}Display;

I just tried to compile with gcc. The original code has a compiling error: "incompatible types when initializing type ‘char *’ using type ‘DisplayGroup’" .Now, there is no more one.

Upvotes: 0

ouah
ouah

Reputation: 145829

In your declaration:

Info groupFields = { 0, {groupType}};

groupType value is of type DisplayGroup which is not the type of the first union display member. A union may only be initialized with a value of the type of its first member, i.e, an initializer of type DisplayString here.

Upvotes: 2

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26121

I hope this explicit definition helps you see what is going on:

Info infoField = { .x = 0, .Display = {.displayString = stringType}};
Info groupFields = { .x = 0, .Display = {.displayGroup = groupType}};

You have to at least define which union variant you choose:

Info infoField = { 0, {.displayString = stringType}};
Info groupFields = { 0, {.displayGroup = groupType}};

Upvotes: 2

Related Questions