我有以下的結構在我正在進行的鬥爭,最終建立某種外殼(最終根據各地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