如何从函数返回字符串文字 [英] How to return a string literal from a function
问题描述
我总是困惑从函数返回一个字符串文字或字符串。我被告知可能会有内存泄漏,因为你不知道内存何时被删除?
I am always confused about return a string literal or a string from a function. I was told that there might be memory leak because you don't know when the memory will be deleted?
例如,在下面的代码中,如何实现 foo()
,以使代码的输出为Hello World?
For example, in the code below, how to implement foo()
so as to make the output of the code is "Hello World"?
void foo ( ) // you can add parameters here.
{
}
int main ()
{
char *c;
foo ( );
printf ("%s",c);
return 0;
}
此外,如果 foo
不是无效的,但您可以返回 char *
,应该是什么?
Also, if the return type of foo()
is not void, but you can return char*
, what should it be?
推荐答案
我假设我们不能修改main。为了让程序正常工作,没有泄漏,你需要一些静态存储:
I'm assuming we cannot modify main. To get your program working without a leak, you need something to have static storage:
void foo(char*& pC) // reference
{
static char theString[] = "thingadongdong";
pC = theString;
}
但实际上,这不是很常规的C ++代码。您将使用 std :: string
和 std :: cout
,这样您就不会担心内存:
But really, this isn't very conventional C++ code. You'd be using std::string
and std::cout
, so you don't have to worry about memory:
std::string foo(void)
{
return "better thingadongdong";
}
int main(void)
{
// memory management is done
std::cout << foo() << std::endl;
}
如果您想知道是否需要手动解除分配,错误。
If you're wondering if something needs to be manually deallocated, it's being done wrong.
这篇关于如何从函数返回字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!