-1

I try to fill the content of a union with something, however I receive an error. here's the code:

struct command
{
    int type;
    int *input;
    int *output;
    union{
        struct command *command[2];
        char **word;
    }u;
};

typedef struct command *command_t;

command_t read_command(){
    command_t main1 = NULL;
    command_t main2 = NULL;
    main1->u->word = (char**)malloc(1);
    main1->u->word[0] = (char*)malloc(1);
    //some other code in here
}

I got an error in "main1->u->word = (char**)malloc(1);" line saying: "invalid type argument of â->â (have âunion â)"

any suggestion? thx

timrau
  • 22,578
  • 4
  • 51
  • 64

2 Answers2

0

It needs to be main1->u.word = .... (dot instead of arrow after u.)

But your code contains multiple other errors which the compiler will not find:

You cannot assign to anything in main1 and main2 since these pointers are NULL pointers. Allocate some memory for them first.

The first malloc just allocates a single byte, but your char* needs 4 or 8 bytes. To make this work use:

main1->u.word = (char**)malloc(sizeof(char*));

assuming you want to allocate an array of char* of length 1.

The second malloc also allocates just a single byte. How much data do you want to store here?

Johannes Overmann
  • 4,914
  • 22
  • 38
0

main1->u is an union, and not a pointer-to-union, therefore you can't use the -> operator on it.

Furthermore, you don't allocate enough space for the pointer (malloc(1) returns a pointer to a memory block which is 1 byte large, and I doubt that that's what sizeof(char **) is). You are also casting the return value of malloc(), which is wrong. What you want is

main1->u.word = malloc(sizeof(*main->u.word));
main1->u.word[0] = malloc(LENGTH_OF_STRING + 1); // for the NUL terminator

instead.

Community
  • 1
  • 1