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 (ie 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();
}
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);
}
You can also make a reference to pointer:
void modify_item(struct item* &s){
struct item *retVal = (struct item*)malloc(sizeof(struct item));
retVal->element = 5;
s = retVal;
}
int main(){
struct item *stuff = NULL;
modify_item(stuff); //After this call, stuff == NULL, why?
cout<<stuff->element;
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.