2012-04-08 126 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(); 
}