26

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

3 Answers 3

38

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Are we not passing the pointer by value in the code below posted by STS Balaji? Does that code work only because we are passing the pointer address (i.e. value) because it's allocated on heap?
35
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();
}

Comments

2

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

1 Comment

This is a very good third alternative to what Doug C mentioned above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.