2014-11-08 25 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