How can string values be returned by a function in C language? | SoloLearn: Learn to code for FREE!

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

1/18/2021 4:13:13 PM

Samir Kaushik

6 Answers

New Answer

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

+4

Arsenic NO! NO! NO! NO! NO! Your function char* fun(char* str) { str = "hello"; return str; } It's BAD! BAD! BAD! DO NOT DO THIS! This is the same as doing char* fun() { char * str = "hello"; return str; } Since the string "hello" is a literal string the pointer being returned is pointing to the literal definition in ram. It has nothing to do with the pointer str in the main function, other than it is of the same type. This is very bad programming. If someone were to write to that pointer address anything could happen to the program Essentially both functions do the same thing. They return a pointer to type char.

+4

The only way to return a char pointer from a function is to use the char pointer return type. However, you can alter a character array from within a function by passing a pointer to the beginning of that array. #include <stdio.h> void fun(char* str) { strcpy(str, "hello"); } char * fun2() { static char * str = "world"; return str; } int main() { char str[32]; fun(str); printf("%s",str); printf(" %s",fun2()); return 0; } Here function fun() copies the string "hello" into the location pointed to by the char pointer passed to it. Note that the pointer str in main is not altered, only the contents of the memory area that it is pointing to gets altered.

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