gpt4 book ai didi

c - 为什么 time.h 中定义的函数 'time' 会返回 NULL?

转载 作者:太空宇宙 更新时间:2023-11-04 07:30:48 28 4
gpt4 key购买 nike

我有代码使用函数“time”和“time.h”中的其他函数,并且“time”每次“time”都返回 NULL(哈哈,虽然不好笑,但在“time”上这很昂贵,可用于me to focus attention towards such) such is re-executed.奇怪的是,这是昨天才开始的。以前在类似但缺少(我一直在添加)代码中使用相同的功能证明是可以的。以下为C89代码:

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

#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1

typedef struct tm tm;

int logf(char input_string[])
{
time_t* current_time_since_epoch;
time(current_time_since_epoch);
if (current_time_since_epoch == NULL)
{
printf("'time' returned NULL.\n");
return EXIT_FAILURE;
}
tm* current_time_calandar_time = localtime(current_time_since_epoch);
if (current_time_calandar_time == NULL)
{
printf("'localtime' returned NULL.\n");
return EXIT_FAILURE;
}
char current_time_textual_representation[20];
strftime(current_time_textual_representation, 20, "%d-%m-%Y %H:%M:%S", current_time_calandar_time);
printf("%s\n", current_time_textual_representation);
printf("%s\n", input_string);
return EXIT_SUCCESS;
}

int main(void)
{
int check_logf = logf("Hello.");
if (check_logf == 0) exit(EXIT_SUCCESS);
else
{
printf("'logf' returned EXIT_FAILURE.\n");
exit(EXIT_FAILURE);
}
}

最佳答案

当您将 time_t 的地址传递给 time() 它将结果存储在该地址。由于您没有分配任何内存来存储结果(您所做的只是声明一个未初始化的指针),您将获得未定义的行为。只需将 NULL 传递给 time,它就会返回值。

time_t current_time_since_epoch = time(NULL);

关于c - 为什么 time.h 中定义的函数 'time' 会返回 NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13894981/

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