0

How can I return a char array from a function?

char c[] = getFloat(val, valid);
char getFloat(float val, bool valid){
 if(valid){
 char stringFloat[16];
 dtostrf(val, 10, 8, stringFloat);
 return stringFloat;
 } else Serial.print("No Float");
 }
asked Aug 5, 2015 at 3:04

2 Answers 2

1

Allocate it in the heap. Don't forget to free it after.

#include <stdlib.h>
#include <string.h>
 ...
char *c = getFloat(val, valid);
use(c);
free(c);
 ...
char *getFloat(float val, bool valid){
 if(valid){
 char stringFloat[16], *ret;
 dtostrf(val, 10, 8, stringFloat);
 ret = strdup(stringFloat);
 return ret;
 } else {
 Serial.print("No Float");
 return NULL;
 }
}
answered Aug 5, 2015 at 3:10
1

An alternative method would be to allocate the string statically inside the function, like this:

const char * getFloat(float val, bool valid){
 if (valid)
 {
 static char stringFloat[16];
 dtostrf(val, 10, 8, stringFloat);
 return stringFloat;
 }
 else 
 return "No Float";
 }

Now we can use that string:

const char * c = getFloat(24.5678, true);

However note that this is only good for one use at a time!

This would not work properly, for example:

const char * c1 = getFloat(24.5678, true);
const char * c2 = getFloat(42.7654, true);

Now c1 and c2 both point to the same piece of memory, so only the last one would be correct. However this restriction may not matter to you. And it saves you having to free memory afterwards, and possibly saves you from heap fragmentation.

answered Aug 5, 2015 at 3:58

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.