Reputation: 1300
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?
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?
}
Upvotes: 26
Views: 90279
Reputation: 21
I would suggest to modify your code like below if the function 'modify_item' intends to change member of structure which is passed as argument.
void modify_item(struct item *s){
s->element = 5;
}
int main(){
struct item *stuff = malloc(sizeof(struct item));
modify_item(stuff);
}
Upvotes: 2
Reputation: 41170
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();
}
Upvotes: 35
Reputation: 272467
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.
Upvotes: 38