程序在使用struct tm时崩溃,除非首先声明time_t

Program crashes while using struct tm unless time_t declared first

本文关键字:声明 time struct tm 崩溃 程序      更新时间:2023-10-16

我试图阻止重新创建车轮。我正在解析一个输入文件,其中一个值是时间。我需要一个数据结构来保存输入文件的所有值,而不是为时间字段创建一个自定义结构,我只想使用ctime的struct tm。

我遇到了一个奇怪的错误,所以希望你们中的一个能帮助我。以下是我的测试代码(用于我的概念证明):

#include <ctime>
#include <cstdio>
int main()
{
int Oldhour = 16;
int OldSecond = 25;
int OldMinute = 20;
time_t seconds;
struct tm * timeinfo;
timeinfo->tm_hour = Oldhour;
timeinfo->tm_min = OldMinute;
timeinfo->tm_sec = OldSecond;

int hour, min, sec;
hour = timeinfo->tm_hour;
min = timeinfo->tm_min;
sec = timeinfo->tm_sec;
printf("%d:%d:%d", hour, min, sec);
return 0;
}

这个编译得很好,它做了我想要的,打印了"16:20:25",所以它以我想要的方式存储信息。但是,如果我删除"time_t seconds;"行,它立即崩溃。

您需要使用malloc在堆栈或堆上分配该结构。具体来说,您声明了一个指向该结构体的指针,而没有为其分配任何存储空间。

试试这个:

#include <ctime>
#include <cstdio>
int main()
{
int Oldhour = 16;
int OldSecond = 25;
int OldMinute = 20;
time_t seconds;
struct tm timeinfo;
timeinfo.tm_hour = Oldhour;
timeinfo.tm_min = OldMinute;
timeinfo.tm_sec = OldSecond;

int hour, min, sec;
hour = timeinfo.tm_hour;
min = timeinfo.tm_min;
sec = timeinfo.tm_sec;
printf("%d:%d:%d", hour, min, sec);
return 0;
}