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? }
Structures can be passed into functions either by reference or by value. An array of structures can also be passed to a function.
You can also pass structs by reference (in a similar way like you pass variables of built-in type by reference). We suggest you to read pass by reference tutorial before you proceed. During pass by reference, the memory addresses of struct variables are passed to the function.
A structure can be passed to any function from main function or from any sub function. Structure definition will be available within the function only. It won't be available to other functions unless it is passed to those functions by value or by address(reference).
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.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With