除非先声明 time_t,否则使用 struct tm 时程序会崩溃
我正在努力防止重复造轮子。我正在解析一个将时间作为值之一的输入文件。我需要一个数据结构来保存输入文件的所有值,而不是为时间字段创建自定义结构,我只想使用 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 秒;”行它立即崩溃。
I am trying to prevent recreating the wheel. I am parsing an input file that has time as one of the values. I need a data structure to hold all of the values of the input file, and instead of creating a custom structure for the time field I want to just use struct tm from ctime.
I'm running into a strange error though, so hopefully one of you can help me out. Here's my test code (for my proof of concept):
#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;
}
This compiles just fine and it does exactly what I want and prints "16:20:25" so it's storing the info the way I want. However if I remove the line "time_t seconds;" it crashes immediately.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用 malloc 在堆栈或堆上分配结构。具体来说,您声明了一个指向该结构的指针,但没有为其分配任何存储空间。
试试这个:
You need to allocate the structure either on the stack or on the heap with malloc. Specifically, you're declaring a pointer to the struct without allocating any storage for it.
Try this: