结构指针在两个不同的函数中表现不同,不确定原因

时间:2015-04-12 23:30:11

标签: c

我遇到的问题是我的“TEST INSIDE BUILD”有效,但不是“TEST OUTSIDE”。代码片段在这里

command_t build_op_command(unsigned code, command_t comone, command_t comtwo)
{
  commad_t s;
  s=malloc(sizeof(*s));
  switch(code)
  {
    case 5:
      s->type=SEQUENCE_COMMAND;
    ...
  }
  s->status=-1;
  s->input=NULL;
  s->output=NULL;
  s->u.command[0]=comone;
  s->u.command[1]=comtwo;
  printf("TEST INSIDE BUILD: %d  and %s",s->u.command[0]->type, s->u.command[0]->u.word[0]);
  s->u.word=NULL;
  s->u.subshell_command=NULL; //not yet implemented
  return s;
  }

...
command_t op_command;
op_command=build_op_command(op_pop(op_s),comone,comtwo);
printf("TEST OUTSIDE: %d  and %s",op_command->u.command[0]->type,op_command->u.command[0]->u.word[0]);
...

command_t是struct命令的指针。我不太确定它为什么在构建函数中正确,但在它之外无法正常工作。任何投入将不胜感激。我遇到了分段错误,我尝试为s-> u.word分配空间,但这似乎没有任何帮助。

struct command
{
  enum command_type type;
  int status;
  char *input;
  char *output;

  union
  {
    struct command *command[2];
    char **word;
    struct command *subshell_command;
  } u;
};

typeder struct command *command_t;

1 个答案:

答案 0 :(得分:1)

您没有提供足够的信息,请发布command_t的定义。

u可能是union

s->u.command[0]=comone;
s->u.command[1]=comtwo;
printf("TEST INSIDE BUILD: %d  and %s",s->u.command[0]->type, s->u.command[0]->u.word[0]);

在第一次printf之后,您初始化此union的其他成员并覆盖command

s->u.word=NULL;
s->u.subshell_command=NULL; //not yet implemented

下一个printf报告不同的内容。

union的所有成员在内存中共享相同的位置,一次不能使用多个成员。