struct command
{
...
union
{
...
char **word; // <-- requires memory to be associated explicitly
} u;
};
...
char* charPtr = "abc";
struct command* cmdPtr; // <-- uninitialized variable
strcpy(cmdPtr->u.word,charPtr); // <-- undefined behavior
cmdPtr
is uninitialized, which means that dereferencing of this pointer invokes an undefined behavior already. Even if you would allocate a memory for this struct
, you also have to allocate the memory for the word
member, otherwise strcpy
tries to copy string to the invalid memory, yielding an undefined behavior again.
Additionally the return value of your main
is not defined and the word
is declared as char**
while strcpy
expects the first argument of type char*
. For example you could do:
struct command cmd;
char myBuffer[255];
char* pBuffer = &myBuffer[0];
cmd.u.word = &pBuffer;
strcpy(*cmd.u.word, "abc");
printf("%s", *cmd.u.word);
or instead of making word
to point to local pointer:
cmd.u.word = malloc(sizeof(char*));
*cmd.u.word = &myBuffer[0];
... but once you start allocating stuff dynamically, be careful to properly free / deallocate it as well.