c - localtime 的结果结构如何在 C 中分配?

标签 c function pointers struct

我正在玩 C 语言的 time.h 文件,它可以帮助我们处理时间/日期函数。

我遇到了:

struct tm * _Cdecl localtime(const time_t *__timer);

...这似乎返回一个指向 tm 结构的指针。我发现按地址返回主要用于返回新的内存分配。

如果是这样,那么上面的返回实际上是如何工作的(struct tm 的返回地址)。返回的对象是否在某处定义?

谢谢

最佳答案

localtime(以及其他一些函数)返回的指针实际上是指向静态分配内存的指针。 所以你不需要释放它,也不应该释放它。

http://www.cplusplus.com/reference/clibrary/ctime/localtime/

This structure is statically allocated and shared by the functions gmtime and localtime. Each time either one of these functions is called the content of this structure is overwritten.

编辑:附加评论中提到的一些内容。

这种共享数据结构的直接结果是 localtime 和类似的函数不是线程安全的。线程安全的解决方案因平台而异。 localtime_r for POSIXlocaltime_s for MSVC .

关于c - localtime 的结果结构如何在 C 中分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8694365/

相关文章:

C中的纸牌游戏,随机播放链表

c - 如何使用 sscanf 将变量存储在文件的一行中?

r - 如何将公式转换为函数,或将公式应用于某些值?

c - 在函数中更新结构

以指针为参数的c++函数问题

c - 从大文件中查找唯一值

c++ - 带三点参数的函数

javascript - 显示函数的参数

c++ - 数组是指针吗?

c - 带 Ada 的 FastCGI