Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a function return string on arduino?

Tags:

c++

arduino

I am making a function in which read serial and match it to a certain value, if it matches then I store a string1 in a variable x, else I try to match the read serial with second string and if it matched then I store string2 in x and so on. Now I want this function to return this string(stored in variable x) to main function from where it has been called.

like image 594
Rishabh Kaushik Avatar asked Sep 20 '25 02:09

Rishabh Kaushik


1 Answers

You have a few options. You can have the caller provide the buffer that will be used to store the return value:

void foo0(char * buf, int maxBufferSize) {
  while(maxBufferSize && *buf = getByteFromSerial()) { //assumes getByte returns 0 for done
    maxBufferSize--;
  }
}  // If you really feel like it, you can alter this to return the original buf

You can have the method itself maintain a buffer that it uses for return values:

char * foo1() {
  static char buf[BUF_SIZE+1];
  int copiedBytes = 0;
  while (copiedBytes<BUF_SIZE && buf[copiedBytes++] = getByteFromSerial());
  buf[copiedBytes] = '\0';
  return buf;   // Note that when you call foo() again, this will be destroyed.
}

You can have the method allocate the buffer:

char * foo2() {
   static char buf[BUF_SIZE+1];
   // do all the stuff from the previous version
   char * retval = malloc(copiedBytes);
   strcpy(retval, buf);
   return retval;
 }

This last solution has a number of problems. Yeah, you have to remember to deallocate, but worse than that, dynamic memory allocation on something with so little memory should scare the hell out of you. For details, look up memory fragmentation. Come to think of it, I've NEVER used malloc on a microprocessor for exactly this reason. When there's so little memory available, you can probably come up with better ways to dynamically assign memory yourself.

My preference is for having the caller provide the buffer. This way, any necessary allocation and deallocation is neatly taken care of on the stack and you don't have the multiple-callers problem that foo1(), above, would stick you with.

void someFunction() {
  char buf[BUFF_SIZE+1];
  fillMyBuffer(buf, BUFF_SIZE);
  doSomethingWithMyBuffer(buf);
}

This way, when someFunction returns, its buffer is no longer taking up memory and I don't have a function in my program that has a static buffer taking up space that may only be used very infrequently.

like image 85
Sniggerfardimungus Avatar answered Sep 22 '25 17:09

Sniggerfardimungus