我不是C++开发人员,我想弄清楚为什么当我从一个函数返回一个C字符串时,我会得到垃圾.
#include <stdio.h>
const char* tinker(const char* foo);
int main(void)
{
const char* foo = "foo";
foo= tinker(foo);
printf(foo); // Prints garbage
return 0;
}
const char* tinker(const char* foo)
{
std::string bar(foo);
printf(bar.c_str()); // Prints correctly
return bar.c_str();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
233 次 |
| 最近记录: |