我开始在 C 中学习 Linux 编程,我遇到了以下情况:
time_t now;
struct tm *local_time;
now = time(NULL);
local_time = localtime(&now);
函数 localtime
是 Linux API 的一部分,它接受一个指向 time_t
的指针,这很好,但为什么它返回一个指向 tm 的指针
结构?
我的问题是 tm
结构在初始化后如何管理?
如果 localtime
静态分配结构,它不能保证结构不会随着程序的进行而被覆盖,如果 tm
结构是动态分配的,那么程序员必须调用 free
结构不再需要。
那么返回指针的 C 函数的正确阶段是什么?
谢谢!
根据manpage for localtime (为清楚起见添加了粗体和斜体):
The localtime() function converts the calendar time timep to broken-down time representation, expressed relative to the user's specified timezone. The function acts as if it called tzset(3) and sets the external variables tzname with information about the current timezone, timezone with the difference between Coordinated Universal Time (UTC) and local standard time in seconds, and daylight to a nonzero value if daylight savings time rules apply during some part of the year. 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. It need not set tzname, timezone, and daylight.
粗体部分表示返回值的行为与您猜测的完全一样,后续调用可能会覆盖先前返回的结构。
您要么需要立即缓存生成的结构,要么使用斜体部分中提到的函数。