【发布时间】:2014-11-08 18:10:53
【问题描述】:
在我最终创建某种 shell 的持续努力中,我有以下结构(最终基于 execvp()。
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
};
然后我使用 malloc 初始化 anyargs 并创建一个字符串数组,每个参数一个字符串传递给 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?
}
【问题讨论】:
-
出于好奇,real
runEntry是什么样子的,因为这个在来自main的调用中有两个参数,但在实际实现中提供了三个.这没有被标记为 C++,最后我检查了(已经有一段时间了,诚然)C 不支持可选参数(不要与可变参数混淆)。runEntry是在main()中使用之前进行原型设计的,还是您只是使用假定int fn()默认的编译器。 -
@WhozCraig 真正的 runEntry 大约有 100 行,并且包含一个 bool *quit - 我在 printUserEntry(userentry); 之后省略了所有内容;调试器告诉我 userentry->anyargs[0] 变空了。
-
和调用到实现的参数不匹配?
-
不是我的实际代码中的参数不匹配,为了清楚起见我没有尝试省略数据 - 我不想做代码转储 - 同样我没有原型
runEntry,在这个问题中包含标题或其他类似内容。 -
我明白,只要您了解这种不匹配很容易导致问题,因此只有您知道的完全红鲱鱼。发布摘要很好(并且高度鼓励)只要它证明了问题并且不会由于剥离而引入切线问题。我希望这很清楚。看起来保罗正在解决你的问题。希望对您有所帮助。
标签: c arrays pointers struct char