Categories
Development

In C, how to create a function that, given a string literal as a parameter, returns a char*? (Without allocating new memory on the heap)

Desired outcome: utilityfun(“&xxx”) must return a pointer to “xxx”. utilityfun(“xxx”) must return a pointer to “*xxx”. #include <stdio.h> #include <string.h> char* utilityfun(char *s) { if(*s==’&’) return s+1; // this case works fine else { char r[strlen(s)+2]; memset(r,’*’,1); strcpy(r+1,s); char* p=r; return p; // !!! p is local to this stack frame! } } void main() […]