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