You can return a char array, but you need to be cautious about how that array comes into existence. Here is an example:
char * foo ()
{
char buf [666] = "But does it get goat's blood out?";
return buf;
} // end of foo
void setup ()
{
Serial.begin (115200);
Serial.println (foo ());
} // end of setup
void loop () {}
This code however has a fundamental flaw, which I will point out before my colleagues do. ![]()
The character array buf has a scope and lifetime only inside foo, and thus although I returned a pointer to it, the pointer becomes invalid outside foo. Thus it prints garbage (as expected).
This "fixes" it:
char * foo ()
{
static char buf [666] = "But does it get goat's blood out?";
return buf;
} // end of foo
void setup ()
{
Serial.begin (115200);
Serial.println (foo ());
} // end of setup
void loop () {}
Now the scope of buf is inside foo, but the lifetime is the whole sketch. This prints correctly, but by making it static I may as well have made it a global variable. The memory (666 bytes) is going to be used, whether or not I am inside foo.
In other words, like this:
char buf [666] = "But does it get goat's blood out?";
char * foo ()
{
return buf;
} // end of foo
void setup ()
{
Serial.begin (115200);
Serial.println (foo ());
} // end of setup
void loop () {}
Now of course, foo is pretty useless.
You can dynamically allocate memory:
char * foo ()
{
char * buf = (char *) malloc (666);
strcpy (buf, "But does it get goat's blood out?");
return buf;
} // end of foo
void setup ()
{
Serial.begin (115200);
Serial.println (foo ());
} // end of setup
void loop () {}
That works, but the memory is never reclaimed. So you could do this:
char * foo ()
{
char * buf = (char *) malloc (666);
strcpy (buf, "But does it get goat's blood out?");
return buf;
} // end of foo
void setup ()
{
Serial.begin (115200);
char * p = foo ();
Serial.println (p);
free (p);
} // end of setup
void loop () {}
That is closer, foo allocates as much memory as it wants to (within reason) and setup does something with the char array, and then frees it.
I would like to write a function returning a char array.Is this possible or do ...
As I hope I have demonstrated, the answer is "yes". But bear in mind you don't have a lot of memory to play with.