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;
}
std::string?using namespace std. It is the C++ Standard Library which is a collection of classes and functions. The built in C++ library routines are kept in the standard namespace. That includes stuff like cout, cin, string, vector, map, etc.