I have the struct:
struct mystruct { int a;};
If I create a function with the struct as an argument,and try to directly return its address:
struct mystruct *modifystruct1(struct mystruct s){ s.a = 5; return &s;}
Compiling with c99 -Wall -Wextra -pedantic
will warn warning: function returns address of local variable [-Wreturn-local-addr]
,which I know I shouldn't do.
However, if I save the address to another variableand try to return that, the warning disappears:
struct mystruct *modifystruct2(struct mystruct s){ struct mystruct *sptr = &s; sptr->a = 5; return sptr;}
Is this okay to do, or is it no different from the above?(and if so, why is there no more warning?)
If not, how can I modify a copy of a struct inside a functionand return a pointer to that struct,safely, preferably without using malloc
?