程序在使用struct tm时崩溃,除非首先声明time_t
Program crashes while using struct tm unless time_t declared first
我试图阻止重新创建车轮。我正在解析一个输入文件,其中一个值是时间。我需要一个数据结构来保存输入文件的所有值,而不是为时间字段创建一个自定义结构,我只想使用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;
}
相关文章:
- .cpp和.h文件中的模板专用化声明
- 未在作用域中声明unordered_map
- C++避免重复声明的语法是什么
- 如何确保C++函数在定义之前声明(如override关键字)
- 错误:未在此范围内声明'reverse'
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 为什么在定义函数之前先声明它
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- #ifdef和未声明的标识符
- 没有显式声明的int[]中的foreach
- 在基于范围的for循环中使用结构化绑定声明
- 在将变量声明为引用时,堆在释放后使用
- C++:无法访问声明的受保护成员
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 在函数内部的声明中初始化数组,并在外部使用它
- Visual Studio中的函数声明和函数定义问题
- c++类声明时,相同的例程,不同的成员变量类型
- C++,'time'没有在这个范围内声明,没有理由