+ 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".

18th Jan 2021, 4:13 PM
Samir Kaushik
Samir Kaushik - avatar
6 Answers
+ 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.
18th Jan 2021, 4:16 PM
Arsenic
Arsenic - avatar
+ 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
18th Jan 2021, 4:26 PM
Arsenic
Arsenic - avatar
+ 1
Please provide some example codes
18th Jan 2021, 4:18 PM
Samir Kaushik
Samir Kaushik - avatar
+ 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).
20th Jan 2021, 3:34 PM
Mike A
Mike A - avatar