ctime 返回 NULL

标签 c

我正在使用 ctime。但是它总是返回空值。所以它以 sprintf 线为核心。它工作得更早。所以不确定为什么它会随机返回 null。

我有以下代码片段:

int main()
{
 char avp_val[50];

 uint32_t date_value=1477069401;

sprintf(avp_val,"%s",ctime((time_t*)(&date_value)));

  return;
}

最佳答案

它对我有用,但代码仍然很奇怪。

我不确定您为什么要使用 uint32_t 来存储时间。它应该是 time_t(如果必须的话,也可以是 int)。时间不是无符号的,可以是负数(听说1970年之前就有时间)。它也不应该是 32 位的;如果你这样做了you'll run out of time in 2038 .现在大多数机器都使用 64 位 time_t

你不应该使用 ctime 因为它重复使用了同一个指针。我怀疑这就是您执行 sprintf 以复制字符串的原因。更好的是,使用 ctime_r 来传递分配的字符串。

这是一种更直接的方法。

#include <stdio.h>
#include <time.h>

int main() {
    time_t date_value = 1477069401;

    char date_str[26];

    ctime_r(&date_value, date_str);

    puts(date_str);

    return 0;
}

关于ctime 返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40200615/

相关文章:

c - "dereferencing"这个词是从哪里来的?

c - inet_ntop 打印不正确的 IPv6 地址

c++ - LD_LIBRARY_PATH 不包含导出路径

c - sscanf 的奇怪行为

c - 删除堆的根没有任何效果

c - 将列表写入文本文件

c - 段错误 11

c - 插入带有公共(public)哨兵的红黑树

c - 递归结构和 malloc()

c - Linux 中 userfaultfd() 系统调用的旧替代方案?