0

Hello I am trying to copy a string into "word" variable. strcpy requires char* type, and my "word" variable is char** type. How do I make it happen? I tried following, but it does not work.

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


main(){
...
char* charPtr = "abc";
struct command* cmdPtr;
strcpy(cmdPtr->u.word,charPtr);
...
}
LihO
  • 41,190
  • 11
  • 99
  • 167
Peter Hwang
  • 971
  • 1
  • 12
  • 25
  • 2
    You start by allocating some memory, as the undefined behavior in this is rampant. – WhozCraig Oct 03 '13 at 09:40
  • 2
    To start with, a pointer to a pointer to `char` is not a string. If anything it *might* be an array of strings. Secondly, in your code snippet you do not actually initialize the structure pointer, so it points to some undefined location. And when you make `cmdPtr` point somewhere valid, then you need to initialize the pointers *in* the structure, including the ones in the array. – Some programmer dude Oct 03 '13 at 09:41
  • 5
    Do you just want to make the program compile, or do you want to to be able to run as well? – David Heffernan Oct 03 '13 at 09:41
  • @DavidHeffernan LOLz, thats an *awesome* question. – WhozCraig Oct 03 '13 at 09:42

1 Answers1

4
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.

LihO
  • 41,190
  • 11
  • 99
  • 167