将结构指针传递给c中的函数

时间:2021-12-06 19:57:29

I'm having a problem with passing a pointer to a struct to a function. My code is essentially what is shown below. After calling modify_item in the main function, stuff == NULL. I want stuff to be a pointer to an item struct with element equal to 5. What am I doing wrong?

我将指向结构的指针传递给函数时遇到问题。我的代码基本上如下所示。在main函数中调用modify_item后,stuff == NULL。我希望stuff是一个指向item结构的指针,元素等于5.我做错了什么?

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?
}

2 个解决方案

#1


24  

Because you are passing the pointer by value. The function operates on a copy of the pointer, and never modifies the original.

因为您按值传递指针。该函数对指针的副本进行操作,从不修改原始函数。

Either pass a pointer to the pointer (i.e. a struct item **), or instead have the function return the pointer.

将指针传递给指针(即结构项**),或者让函数返回指针。

#2


19  

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);

or

要么

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();
}

#1


24  

Because you are passing the pointer by value. The function operates on a copy of the pointer, and never modifies the original.

因为您按值传递指针。该函数对指针的副本进行操作,从不修改原始函数。

Either pass a pointer to the pointer (i.e. a struct item **), or instead have the function return the pointer.

将指针传递给指针(即结构项**),或者让函数返回指针。

#2


19  

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);

or

要么

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();
}