Trouble returning char array / string

The following code isn't printing the correct result to the serial monitor. It should print 02. Can someone tell me why?

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  char str[2];
  //Serial.println(text(2));
  *str = text(34);
  Serial.println(str);
}

char * text(int num)
{
  {
    char str[2];
    sprintf(str, "%02d", num);
    return str;
  }
}
1 Like
char str[2];
    sprintf(str, "%02d", num);

{cough} terminator

I am not why you think an extra pair of braces is necessary, but the str[] returned from the function is in the bit bucket after the function returns:

http://c-faq.com/malloc/retaggr.html

Further your str in the text goes out of scope when the text function finishes so your pointer is pointing into nowhere.

Lastly, str in loop is an array. It is lost at the moment that you assign a value to that str.

"Going out of scope" is not the problem. The problem is that it is an automatic variable allocated on the stack, and it technically* disappears when the function returns.

A static variable would still be "out of scope" after the function returns, but still be available for pointer access.

*"technically" because you might get lucky and have it persist a bit before it gets clobbered.

like this:

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  Serial.println(text(12));
  char str[3];
  strcpy(str, text(34));
  Serial.println(str);
  while(true){}
}

char* text(int num)
{
  static char str[3];  // using static keyword guarantees you get a pointer to good stuff
  sprintf(str, "%02d", num);
  return str;
}
1 Like

Got it working by making the char array global. Here's the code now and it seems to work fine.

char str[3];

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  str[3] = text(2);
  Serial.println(str);
}

char * text(int num)
{
  sprintf(str, "%02d", num);
  return str;
}

PickyBiker:
...working by making the char array global. ...

why not... globals are the panacea for all Arduino woes

think globally, act locally ;D

Does that work?

If you are writing to the global str, there is no reason for the return, and in fact, I don't know what this is going to do:

str[3] = text(2);

since str[3] does not even exist. You are writing a pointer into the locations just after string, which will bite you in the butt someday.

Have text() return void and call it like this:

text(2);

2 Likes