0

How can i receive a string in a function returned by another function in C? is this process right?

int main () { char a[100], c[100]; //code ; c [100] = function (ara); } void function (ara) { //code; return ara; }

18th Jun 2020, 9:35 AM
WaYR🇧🇩
WaYR🇧🇩 - avatar
1 Resposta
0
If the function returns a string it must be heap allocated or return a string parameter, otherwise that string is local to the function and will be destroyed when the function exits. For heap allocated strings you'll need a char pointer to hold the returned value. As an example: char *new_string(const char *text) { char *s = malloc(strlen(text) + 1); return s ? strcpy(s, text) : NULL; } In main(): char *s = new_string("The C Programming Language"); puts(s ? s : "Allocation failure"); free(s); new_string() is doing what strdup() does on UNIX-based systems, it returns a mutable heap-allocated string and copies the string parameter into it. But you don't have to do it that way, you can pass a size and return an empty string with a few changes. It depends on what you want your function to do.
18th Jun 2020, 10:34 AM
Gen2oo
Gen2oo - avatar