简体   繁体   中英

How to use mktime() without changing the original tm struct?

I've recently came up with a problem using the code:

time_t today_t;
time(&today_t);
tm *today = localtime(&today_t);

time_t tomorrow_t = mktime(today);
tomorrow_t += 86400;
tm *tomorrow = localtime(&tomorrow_t);

The problem is that my object changes right after i use localtime(&tomorrow_t) to create object, and values of both objects become equal. 对象在我使用localtime(&tomorrow_t)创建对象后立即更改,并且两个对象的值变得相等。 I don't really understand this behavior. Any help, please?

localtime uses a single static variable for the tm struct and returns a pointer to it. Thus, today and tomorrow will have the same address.

There is a reentrant version localtime_r that takes a second argument where you can specify where the struct data is placed.

Quoting the Linux man page for the localtime function:

The return value points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions. The localtime_r() function does the same, but stores the data in a user-supplied struct.

So if you call localtime() twice, it will return the same pointer value each time, overwriting it with the new value. today is a struct tm* pointer, which you own; *today is a struct tm object, which is owned by the C library.

Either copy the structure (not the pointer) to another struct tm object after the call or use localtime_r which writes to a structure that you supply. ( localtime_r is not 100% portable; it's defined by POSIX, but not by the ISO C standard.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM