Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing struct pointer to function in c

Tags:

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? } 
like image 348
Swiss Avatar asked Apr 08 '12 21:04

Swiss


People also ask

Can you pass a struct into a function in C?

Structures can be passed into functions either by reference or by value. An array of structures can also be passed to a function.

Are structs passed by reference C?

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.

Can we pass structure as a function argument?

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).


2 Answers

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.

like image 152
Oliver Charlesworth Avatar answered Sep 19 '22 15:09

Oliver Charlesworth


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(); } 
like image 38
Doug Currie Avatar answered Sep 20 '22 15:09

Doug Currie