gpt4 book ai didi

c++ - 两个独立的 tm 结构相互镜像

转载 作者:搜寻专家 更新时间:2023-10-31 00:05:07 26 4
gpt4 key购买 nike

这是我目前的情况:

  • 我有两个 tm 结构,都设置为当前时间
  • 我更改了其中一个结构中的小时
  • 变化神奇地发生在另一个结构中....
  • 如何防止这种情况发生?我需要能够比较并知道两个不同时间之间的秒数——当前时间和 future 时间。我一直在使用 difftime 和 mktime 来确定这一点。我认识到我在技术上不需要两个 tm 结构(另一个结构可能只是加载了原始时间的 time_t),但我仍然有兴趣了解为什么会发生这种情况。

void Tracker::monitor(char* 缓冲区){

// time handling
time_t systemtime, scheduletime, currenttime;
struct tm * dispatchtime;
struct tm * uiuctime;
double remainingtime;


// let's get two structs operating with current time
dispatchtime = dispatchtime_tm();
uiuctime = uiuctime_tm();

// set the scheduled parameters
dispatchtime->tm_hour = 5;
dispatchtime->tm_min = 05;
dispatchtime->tm_sec = 14;

uiuctime->tm_hour = 0;

// both of these will now print the same time! (0:05:14)
// what's linking them??

// print the scheduled time
printf ("Current Time : %2d:%02d:%02d\n", uiuctime->tm_hour, uiuctime->tm_min, uiuctime->tm_sec);
printf ("Scheduled Time : %2d:%02d:%02d\n", dispatchtime->tm_hour, dispatchtime->tm_min, dispatchtime->tm_sec);

struct tm* Tracker::uiuctime_tm(){
time_t uiucTime;
struct tm *ts_uiuc;

// give currentTime the current time
time(&uiucTime);

// change the time zone to UIUC
putenv("TZ=CST6CDT");
tzset();

// get the localtime for the tz selected
ts_uiuc = localtime(&uiucTime);

// set back the current timezone
unsetenv("TZ");
tzset();

// set back our results
return ts_uiuc;
}

struct tm* Tracker::dispatchtime_tm(){
time_t currentTime;
struct tm *ts_dispatch;

// give currentTime the current time
time(&currentTime);

// get the localtime for the tz selected
ts_dispatch = localtime(&currentTime);

// set back our results
return ts_dispatch;
}

最佳答案

你必须这样做:

struct tm* temp_tm;
struct tm dispatchtime; // No longer a pointer
struct tm uiuctime; // No longer a pointer

temp_tm = dispatchtime_tm();
dispatchtime = *temp_tm; // Member to member copy

temp_tm = uiuctime_tm();
uiuctime = *temp_tm; // Member to member copy

这样您将保留 tm 结构的本地拷贝。此结构在标准库内部分配,每次调用 localtime 将指向相同的内存地址!

关于c++ - 两个独立的 tm 结构相互镜像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3047002/

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