[英]How to create and return string from function?
想从一个函数生成一个字符串,以便格式化某些数据,因此该函数应该返回一个字符串。
试图做“显而易见的”,如下所示,但这会打印垃圾:
#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;
}
我认为这是因为函数中定义的用于res
变量的堆栈上的内存在值写入之前就被覆盖了,也许是在printf
调用使用堆栈时。
如果我移动char res[13];
在函数外部,从而使其成为全局函数,然后起作用。
那么答案是拥有可用于结果的全局char缓冲区(字符串)吗?
也许做类似的事情:
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;
}
不要理会20世纪初期的东西。 在上个世纪末,我们已经有了std::string
,这很简单:
#include <iostream>
#include <string>
std::string hello_world()
{
return "Hello world\n";
}
int main()
{
std::cout << hello_world();
}
最好的解决方案是使用std::string
。 但是,如果必须使用数组,则最好在调用函数中分配它(在本例中为main()
):
#include <iostream>
#include <cstring>
void hello_world(char * s)
{
memcpy(s, "Hello world\n", 13);
}
int main(void)
{
char mys[13];
hello_world(mys);
std::cout<<mys;
return 0;
}
不过,如果您想编写纯C代码,则可以执行类似的操作。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *HelloWorld(char *s, int size)
{
sprintf(s, "Hello world!\n");
return s;
}
int main (int argc, char *argv[])
{
char s[100];
printf(HelloWorld(s, 100));
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.