A string is a block of memory of variable length, and C cannot returns such objects (at least not without breaking compatibility with code that assumes strings cannot be returned)
You can return a pointer to a string, and in this case you have two options:
Option 1. Create the string dynamically within the function:
char *funzione (void)
{
char *res = malloc (strlen("Example")+1); /* or enough room to
keep your string */
strcpy (res, "Example");
return res;
}
In this case, the function that receives the resulting string is responsible for deallocate the memory used to build it. Failure to do so will lead to memory leaks in your program.
int main()
{
char *str;
str = funzione();
/* do stuff with str */
free (str);
return 0;
}
Option 2. Create a static string inside your function and returns it.
char *funzione (void)
{
static char str[MAXLENGTHNEEDED];
strcpy (str, "Example");
return str;
}
In this case you don't need to deallocate the string, but be aware that you won't be able to call this function from different threads in your program. This function is not thread-safe.
int main()
{
char *str;
str = funzione();
/* do stuff with str */
return 0;
}
Note that the object returned is a pointer to the string, so on both methods, the variable that receives the result from funzione()
is not a char array, but a pointer to a char array.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…