1

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");
    }

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;
  }
}
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.