2012-04-08 78 views
14

我在將函數指針傳遞給結構時遇到了問題。我的代碼基本上是如下所示。在主函數中調用modify_item之後,stuff == NULL。我想要的東西是一個指向元素等於5的項目結構的指針。我在做什麼錯了?將結構指針傳遞給函數c

void modify_item(struct item *s){ 
    struct item *retVal = malloc(sizeof(struct item)); 
    retVal->element = 5; 
    s = retVal; 
} 

int main(){ 
    struct item *stuff = NULL; 
    modify_item(stuff); //After this call, stuff == NULL, why? 
} 

回答

22

因爲你是按值傳遞指針。該功能在指針的副本上運行,並且永遠不會修改原件。

要麼將​​指針指向指針(即struct item **),要麼讓函數返回指針。

17
void modify_item(struct item **s){ 
    struct item *retVal = malloc(sizeof(struct item)); 
    retVal->element = 5; 
    *s = retVal; 
} 

int main(){ 
    struct item *stuff = NULL; 
    modify_item(&stuff); 

struct item *modify_item(void){ 
    struct item *retVal = malloc(sizeof(struct item)); 
    retVal->element = 5; 
    return retVal; 
} 

int main(){ 
    struct item *stuff = NULL; 
    stuff = modify_item(); 
}