C函数返回指向结构的指针

标签 c pointers struct malloc

<分区>

我开始在 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.

粗体部分表示返回值的行为与您猜测的完全一样,后续调用可能会覆盖先前返回的结构。

您要么需要立即缓存生成的结构,要么使用斜体部分中提到的函数。

关于C函数返回指向结构的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32285125/

相关文章:

c - fcntl() 和 F_GETFL : strange result

c - 需要帮助解决警告 : dereferencing type-punned pointer will break strict-aliasing rules

c - struct C 中的映射结构

c - 无法声明结构的动态数组

c - 将函数地址存储到全局变量中

c - 在 C 中复制两个相邻字节的最快方法是什么?

c++ - 名称映射--\\.\PhysicalDrive 到\\.\SCSI

c++ - 指向成员函数语法的指针

c++ - 为什么 int *const p1;在 int *p1; 工作正常时导致错误?

c++ - 从文件中读入结构数组