gpt4 book ai didi

ctime 返回 NULL

转载 作者:太空宇宙 更新时间:2023-11-04 03:27:13 26 4
gpt4 key购买 nike

我正在使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com