2015-04-12 16 views
-1

我遇到了“我的内部构建测试”工作但没有“测试外部”的问题。代码的片段是这里结构指针在两个不同函数中表现不同,不知道为什么

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为结构命令的指针。我不太确定为什么它可以在构建函数中正确使用,但不能在其外部正确工作。任何投入将不胜感激。我遇到了分段错误,我试图为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; 
+0

难道你就是一个工会吗? –

+0

是的,抱歉,因为模糊。编码非常困难,我似乎无法理解发生了什么。也许我需要为工会分配空间,但这没有任何意义,因为我没有问题地存储u.word。 – Jack

+0

如果你将测试移动到's-> u.word = NULL;'后面,你会发现同样的问题,这与函数无关 –

回答

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的所有成员在内存中共享相同的位置,一次不能使用多个成员。

+0

那么在这种情况下,所有三个命令将共享相同的联合空间?这是第一次与工会打交道,这让我感到困惑。所以在这个范围内创建的所有命令都共享同一个联盟?如果是的话,我可以看看为什么s-> u.com和[0] - > u.word [0]可能会导致问题,但s-> u.com和[0] - >类型如何也会产生问题? – Jack

+0

@Jack:每个'union u'的所有成员共享相同的空间。你不能初始化其中的一个以上,只能读你写的。如果它们确实被正确分配,这个“联合”的不同实例是不相交的。在你的情况下,'command_t'结构的'type'成员应该告诉你哪个成员可以访问。 – chqrlie

相关问题