4

How to return a local char array from a function which has the return type as const char*?
Note: I want a way without using std::string

const char * getXXX()
{
  char buf[32];
  sprintf(buf,"XXX%d",i);  // some manipulation
  return buf; // How to return???
}
7
  • @Spook , if I use "new" key word inside the function, where should I delete that pointer? Commented Feb 19, 2014 at 8:49
  • 4
    Can you please elaborate on why you don't want to use std::string? Using the standard library will make your life as a C++ programmer so much easier! Commented Feb 19, 2014 at 8:50
  • @Nadaraj I've already answered that :) If you allocate memory inside your function, the caller is then responsible for freeing it. Unless, of course, you use std::string - then you can simply return it by value and don't have to worry about freeing allocated memory. Commented Feb 19, 2014 at 8:52
  • @Joachim Pileborg .. since i'm using a lot of sprintf statements inside the function, i need a char buf. So, i was looking a solution without assigning the char buf again to a temp string to return the value. Commented Feb 19, 2014 at 9:09
  • 1
    You do know about std::ostringstream? Using it you can use all the normal C++ stream output formatting functionality, and still get a std::string as output. No fixed-size buffers, no special case handling for strings, type safety, automatic appending to the string. All of those things you can't get by using old C-style sprintf and family. Commented Feb 19, 2014 at 9:11

2 Answers 2

2
const char * getXXX()
{
  static char buf[32];
  sprintf(buf,"XXX%d",i);
  return buf;
}

This will work

Sign up to request clarification or add additional context in comments.

Comments

1

As you correctly noticed, you should not return buf (this is a local variable and its memory will be freed after the function returns). The solution is to allocate some memory and return it.

char * returnBuf = new char[32];

memcpy(returnBuf, buf, 32 * sizeof(char));

return returnBuf;

Remember though, that the caller will be responsible for freeing memory returned by getXXX:

char * result = GetXXX();

// Process

delete[] result;

Comments

Your Answer

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.