2014-05-02 81 views
3

我有一個問題,這聽起來很蠢,但我只是不明白。我嘗試使用下面的結構爲列表編程一個小的shell:結構上的指針無法複製到函數內的另一個指針

struct shellvalue { 
    char* word; 
    char isorder; 
    char isarg; 
    char ispipe; 
    char isamp; 
    unsigned int wordcount; 
    unsigned int ordercount; 
    struct shellvalue* next; 
}; 

我開始在主法兩個指針與

struct shellvalue* start; 
struct shellvalue* current; 

然後我分配現在內存的第一個元素:

void addtoken(char* word, int counter, struct shellvalue* start, 
    struct shellvalue* current) 
{ 
    if (counter == 0) 
    { //creating first element 
    size_t structsize = sizeof(struct shellvalue); 
    struct shellvalue* tmp = (struct shellvalue*) malloc(structsize); 
    tmp->word = malloc(strlen(word) + 1); 
    strcpy(tmp->word, word); 
    start = tmp; 
    start->next = NULL; 
    current = start; 
    } 
    else 
    { // append new element 
    struct shellvalue* new = (struct shellvalue*) malloc(
     sizeof(struct shellvalue)); 
    new->word = malloc(strlen(word) + 1); 
    strcpy(new->word, word); 
    current->next = new; 
    current = new; 
    } 
} 

但是,當我嘗試做

start = tmp; 

我可以在調試器中看到,該啓動仍然具有來自main-Method的NULL值。兩個指針似乎是同一類的我,我得不到warnigs或任何與此compilertags

-Wall -ansi -Wconversion -pedantic -m64

我真的不知道,我做錯了。

+5

C通過值傳遞。函數內部的'start'只是傳遞給調用它的函數的**拷貝**。 – alk

+1

1+使用調試器! :-) – alk

回答

1

您的分配start = tmp只更改中start的值。由於指針是按值傳遞的,所以這不會改變函數外部的指針start。爲了實現這一點,你必須通過一個指針的指針到你的函數:

void addtoken(char* word, int counter, struct shellvalue** start, struct shellvalue** current) { 
    // .. 
    // replace assignments to start/current with: 
    *start = tmp 
    // .. 
} 

然後調用你的函數:

struct shellvalue* start; 
struct shellvalue* current; 

addToken(word, counter, &start, &current); 

我建議的替代方法:

使用結構來保存你的指針,並將指針傳遞給你的函數:

struct shellvalue_list { 
    struct shellvalue* start; 
    struct shellvalue* end; 
}; 

void addtoken(struct shellvalue_list* list, char* word, int counter) { 
    // .. 
    list->start = tmp; 
    // .. 
} 

這是C中面向對象代碼的常見習慣用法。

+0

哦,我怎麼會這麼盲目。非常感謝你! –

相關問題