Passing struct pointer to function in c

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

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.

Tags:

C

Pointers

Struct