Yes and no. It's correct in the way that it will compile, and the compiler will return the address of "mystr".
However, it is incorrect in the sense that the string will be "lost" and almost certainly overwriten once the function is left. This is because "mystr" is a local variable, and you are just passing the address back to the calling function. That address is only valid within the function, not after the function has been left (returned from).
There are three (suitable) options to do this:
1. Use a static local variable. This is a "global variable" but it's only visible within the function. This is not suitable if your application ever gets multi-threaded, and since you there is only ever ONE string there, if another call is made, the original value is changed. E.g:
Code:
char *myfunc(const char *s)
{
static char local[100];
strncpy(local, s, sizeof(local)-1);
return local;
}
int main()
{
char *a, *b;
a = myfunc("abc");
b = myfunc("def");
printf("a=%s, b=%s\n", a, b);
}
// Output:
a=def, b=def
2. Pass in a string as an argument to the function, and fill it in. Don't forget to pass along the length, so that the function can make sure it doesn't overwrite the end of the string.
3. Allocate memory using malloc - but you must then free it somewhere, or your application will leak memory and if it runs for a long enough time may expand to take up all the memory available in the machine.
--
Mats