【问题标题】:Return a const char *返回一个常量字符 *
【发布时间】: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 问题...回答了您的问题。您不能返回指向堆栈中某物的指针。
  • 使用mallocnew,buff是暂时的。通常它崩溃了,你得到了垃圾。它的UB
  • 我想知道为什么在C++中有std::string时使用char *
  • 只是为了学习旧的好方法;)

标签: c++ function char constants


【解决方案1】:

将你的函数更改为返回std::string,一切都会好起来的。除了返回类型之外,您不需要进行任何进一步的更改。如果消费者需要原始的char const *,请在结果字符串上调用c_str() 成员函数。

【讨论】:

  • @Naster:我不能强迫你的想法,但如果你问我,你宁愿学习C++!
  • @Naster 而不是“char *buf;”和“buf = new char[20];”尝试:“静态字符缓冲区 [20];”或者对于您的第一个示例代码,只需在“char buf[20];”前面放一个“static”
猜你喜欢
  • 1970-01-01
  • 2015-02-18
  • 1970-01-01
  • 1970-01-01
  • 2012-11-12
  • 1970-01-01
  • 2019-03-13
  • 2016-09-14
  • 2020-06-19
相关资源
最近更新 更多