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);
...
}
有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top