我有以下的结构在我正在进行的斗争,最终建立某种外壳(最终根据各地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?
}
出于好奇,什么是真正的* *'runEntry'的样子,因为这个函数在'main'的调用中有两个参数,但在实际实现中有三个参数。这是没有标签的C++,最后我检查了(一段时间,诚然)C不支持可选参数(不要与可变参数混淆)。 'runEntry'在它在'main()'中使用之前是原型的,还是你只是使用编译器假定'int fn()'default。 – WhozCraig 2014-11-08 18:24:08
@WhozCraig真正的runEntry大约100行,包含一个布尔*退出 - 我省略了printUserEntry(userentry)后的所有内容。调试器告诉我userentry-> anyargs [0]变空了。 – davidhood2 2014-11-08 18:26:47
从* call *到* implementation *的参数不匹配? – WhozCraig 2014-11-08 18:28:23