I found a similar question and solutions for that here – returning a local variable from function in C
But came up with another solution for same issue and would like to ask you to evaluate it, is it correct or not?
int myfunction (char **returnval) {
int isvalue = 0;
char *d;
d = "Lorem";
*returnval = d;
return isvalue;
}
int main(int argc, char **argv) {
int func_return;
char *myvar;
func_return = myfunction(&myvar);
printf("myvar=[%s]\n", myvar);
return 0;
}
Output: myvar=[Lorem]
Is that code correct? The memory used by vars won’t be lost because of function scope?
Thank you.
String literals are static, i.e. the memory used to hold the characters
Loremis not used to hold anything else for the duration of the program. Thus, returning an address to such a string is safe.This is the same as doing
which is perfectly fine and a common thing to do, for instance when mapping
enumvalues to symbolic strings:Code like this is often (in practice) made way harder to read by making it more DRY, using macros to implement the
casestatements.