2014-11-08 62 views
0

我有以下的结构在我正在进行的斗争,最终建立某种外壳(最终根据各地execvp()失去的char **内容数组传递在C函数时,

struct commands { 
    char cmdname[30]; // The name of the command 
    enum ActionType action; /* char action[30]; what action to take */ 
}; 

struct userinput { 
    struct commands theaction; //The chosen action 
    char cmdentered[100]; // The cmd entered 
    char **anyargs; //The tokenised command 
    int argcount; //Argument count 
}; 

我初始化anyargs使用malloc创建一个字符串数组,每个参数一个字符串传递给execvp。

然后我得到用户输入,将输入转换成存储在anyargs中的标记并检查字符串以找出什么样的需要采取行动并将其存储在枚举中。

所有这些方法都是通过将指针传递给结构userinput作为方法参数来完成的,该方法工作正常。但是,当我将指针传递给嵌套函数时,char** anyargs变空。

我希望我添加的代码提供了解决方案的答案!另一个观察 - 当传递给函数内部的函数时,指针的实际值不会改变 - 仅仅是指针的解引用内容。

任何帮助将非常感激地收到!我试图将代码剥离到我认为会导致问题的地方! 谢谢!

int main() { 

    struct commands cmdlist[4]; //Array of structures with all commands in them 
    memset(cmdlist, 0, sizeof(cmdlist)); 

    struct userinput userentry = { { { 0 } } }; //Structure containing input 
    userentry.theaction = cmdlist[0]; //Initialize empty command 
    userentry.anyargs = calloc(100, sizeof(char)); 

    runEntry(&userentry, cmdlist); //Pass struct to function 

    free(userentry.anyargs); 

    return 0; 
} 

int runEntry(struct userinput *userentry, struct commands thecmds[]) { 
    int retval = 0; 
    int childpid = 0; 
    int processStatus; 
    printf("\n ... running cmd: \n\n"); 

    printUserEntry(userentry); //in printUserEntry, 
           //userentry->anyargs[0] = NULL - why? 
} 
+0

出于好奇,什么是真正的* *'runEntry'的样子,因为这个函数在'main'的调用中有两个参数,但在实际实现中有三个参数。这是没有标签的C++,最后我检查了(一段时间,诚然)C不支持可选参数(不要与可变参数混淆)。 'runEntry'在它在'main()'中使用之前是原型的,还是你只是使用编译器假定'int fn()'default。 – WhozCraig 2014-11-08 18:24:08

+0

@WhozCraig真正的runEntry大约100行,包含一个布尔*退出 - 我省略了printUserEntry(userentry)后的所有内容。调试器告诉我userentry-> anyargs [0]变空了。 – davidhood2 2014-11-08 18:26:47

+1

从* call *到* implementation *的参数不匹配? – WhozCraig 2014-11-08 18:28:23

回答

1

你分配值得anyargschar *元素的100个字节。不过,您尚未初始化这些指针。 anyargs[0]恰巧包含NULL这一事实很好,但不能保证。 malloc()不会初始化分配的空间。

换句话说,当你说:

userentry.anyargs = malloc(100); 

你创建:

userentry.anyargs = { 
    ???, // uninitialized char * 
    ???, // and another 
    ???, // and another 
    ... 
    ??? // (100/sizeof(char *)) entries later 
}; 

你可以明确地初始化那些为NULL的循环:

for (i = 0; i < (100/sizeof(char *)); ++i) 
    userentry.anyargs[i] = NULL; 

(或者使用calloc()而不是malloc()确保一切都清零)。

,或者你可以分配一些空间给他们:

for (i = 0; i < (100/sizeof(char *)); ++i) 
    userentry.anyargs[i] = malloc(50); // or some other length 

或只是将它们直接在runEntry()

userentry.anyargs[0] = "foo"; 
userentry.anyargs[1] = strdup(something); 
+0

或者可能意识到'100/sizeof(char *)'实际上并不需要。 – 2014-11-08 18:24:10

+0

几乎可以肯定的是,但这远不是问题的关键。 – 2014-11-08 18:25:12