+ 1
How can string values be returned by a function in C language?
Please provide a code containing such function. I want to return string values and use them in recursion. The langauge should be "C".
6 Respuestas
+ 4
You can always return a pointer pointing to the first element of the array from a function and make use of the fact that they are stored continuously in memory.
+ 2
Samir Kaushik check this out
In this example, I have used 2 different ways to do so 👇
https://code.sololearn.com/c6p389u3YIqE/?ref=app
+ 1
Please provide some example codes
+ 1
The real problem is that fun() is not const correct. It could've been written as:
const char *fun(const char *str)
{
str = "Hello";
return str;
}
where assignment to a non-const char would generate a compiler warning. Returning read-only strings is completely valid (given that they're declared const).
const char *ptr = fun(ptr); /* This is fine */
char *ptr = fun(ptr); /* Generates a warning */
This string will not be modifiable. If you want a modifiable string you have to allocate memory or set aside a buffer to copy over the contents of the string (as Martin Taylor pointed out).