【发布时间】:2012-08-14 19:38:04
【问题描述】:
我写了一个返回当前日期的函数。在函数内部,我“计算”结果并且它工作,但是当我“计算”函数时,它不起作用。我有垃圾。
const char* engineCS::getDate() const
{
time_t t = time(0);
struct tm *now = localtime(&t);
char buf[20];
strftime(buf, sizeof(buf), "%Y-%m-%d %X", now);
cout << buf << endl;
return buf;
}
示例: 内部 : 2012-02-02 00:00:00 外面:?????fv
怎么了? 类似问题:Functions and return const char*
谢谢
编辑: 现在有什么问题?对不起,我做的 VB.NET 太多了……
const char* engineCS::getDate() const
{
time_t t = time(0);
struct tm *now = localtime(&t);
char *buf;
buf = new char[20];
strftime(buf, sizeof(buf), "%Y-%m-%d %X", now);
cout << buf << endl;
return buf;
}
【问题讨论】:
-
您正在返回一个指向本地的指针。不要那样做。
-
您链接到的 SO 问题...回答了您的问题。您不能返回指向堆栈中某物的指针。
-
使用
malloc或new,buff是暂时的。通常它崩溃了,你得到了垃圾。它的UB -
我想知道为什么在C++中有
std::string时使用char *? -
只是为了学习旧的好方法;)
标签: c++ function char constants