How to create and return string from function?

  • A+
Category:Languages

Would like to generate a string from a function, in order to format some data, so the function should return a string.

Tried to do the "obvious", shown below, but this prints garbage:

#include <iostream> #include <string>  char * hello_world() {     char res[13];     memcpy(res, "Hello world/n", 13);     return res; }  int main(void) {     printf(hello_world());     return 0; } 

I think this is because the memory on the stack used for the res variable, defined in the function, is overwritten before the value can be written, maybe when the printf call uses the stack.

If I move char res[13]; outside the function, thus makes it global, then it works.

So is the answer to have a global char buffer (string) that can be used for the result?

Maybe doing something like:

char * hello_world(char * res) {     memcpy(res, "Hello world/n", 13);  // 11 characters + newline + 0 for string termination     return res; }  char res[13];  int main(void) {     printf(hello_world(res));     return 0; } 


You are programming . That's not bad, but your question is about so this is the solution for the question you asked:

std::string hello_world() {     std::string temp;      // todo: do whatever string operations you want here     temp = "Hello World";      return temp; }  int main() {     std::string result = hello_world();      std::cout << result << std::endl;      return 0; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: