gpt4 book ai didi

c - localtime() 函数显示两个相等的日期

转载 作者:行者123 更新时间:2023-11-30 16:37:01 25 4
gpt4 key购买 nike

为什么当我尝试显示 2 个具有不同参数的日期时,我将其放入 localtime() 函数,控制台显示 2 个相等的日期?

这是我的代码:

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

int main() {
time_t time1, time2;
struct tm *timeinfo1, *timeinfo2;
char *time1str, *time2str;

time1 = 3600;
time2 = 3720;
timeinfo1 = localtime(&time1);
timeinfo2 = localtime(&time2);

time1str = asctime(timeinfo1);
time2str = asctime(timeinfo2);
puts(time1str);
puts(time2str);

getch();
return 0;
}

最佳答案

在两次调用 localtimeasctime 之间,数据不会持续存在。您必须将数据复制到某个地方。这是更正的示例(strncpy 仍然有一些问题):

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

int main() {
time_t time1, time2;
struct tm timeinfo1, timeinfo2, *ti;
char time1str[256], time2str[256], *tstr;

time1 = 3600;
time2 = 3720;
ti = localtime(&time1);
memcpy(&timeinfo1, ti, sizeof(*ti));
ti = localtime(&time2);
memcpy(&timeinfo2, ti, sizeof(*ti));

tstr = asctime(&timeinfo1);
strncpy(time1str, tstr, sizeof(time1str) - 1);
tstr = asctime(&timeinfo2);
strncpy(time2str, tstr, sizeof(time1str) - 1);

puts(time1str);
puts(time2str);

return 0;
}

关于c - localtime() 函数显示两个相等的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48144149/

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