功能和返回为const char * [英] Functions and return const char*
问题描述
const char* test(bool i)
{
const char t[] = "aa\n";
const char* p = "bbb\n";
if(i)
return p;
return t;
}
int main(array<System::String ^> ^args)
{
printf(test(true));
printf(test(false));
return 0;
}
这将返回诸如此类的东西:
That returns something of sort:
bbb
%^&$^$%
很显然,测试(假)返回一个指向一个局部变量。的问题是,p是也局部变量。为什么BBB \\ n时,存储在函数返回后不清洗。我想为const char []是国际preTED同样的方式为const char *,但是,因为它似乎是不正确的。
It is clear that test(false) returns a pointer to a local variable. The question is that p is also local variable. Why the memory for "bbb\n" is not cleaned after the function returns. I thought const char[] is interpreted same way as const char* but it is not true as it seems.
推荐答案
P
是一个局部变量,您可以通过值返回,而是指向了一个字符串文字,它驻留在只读存储器,而不是分配给方法自动记忆。
p
is a local variable, which you return by value, but points to a string literal, which resides in read-only memory, not in the automatic memory allocated for the method.
返回 T
和使用它确实导致不确定的行为。
Returning t
and the using it indeed results in undefined behavior.
另外,不要以为指针和数组的是相同的。
Also, don't think of pointers and arrays to be equivalent.
这篇关于功能和返回为const char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!