1

我正在尝试制作一个 callendar,因此我使用 time_t 和 localtime_s 来存储时间和日期信息,然后将其存储在 Calendar 类的各个成员中:

void Callendar::Initialize()
{
    time_t now = time(0);
    tm *localTime = null;
    localtime_s(localTime, &now);

    LocalSeconds = localTime->tm_sec;
    LocalMinutes = localTime->tm_min;
    LocalHours = localTime->tm_hour;
    LocalDays = localTime->tm_mday;
    LocalMonths = localTime->tm_mon;
    LocalYears = localTime->tm_year;
    DaysSinceSunday = localTime->tm_wday;
    DaysSinceJanuaryFirst = localTime->tm_yday;
    HoursDaylightSavings = localTime->tm_isdst;
}

所有编译都很好,但是在运行时我得到:

调试断言失败!

程序:C:\Users\MyPC\Desktop\Framework\Framework\Debug\Framework.exe 文件:f:\dd\vctools\crt_bld\self_x86\crt\src\loctim64.c 行:69

表达式:( ptm != NULL )

关闭失败的断言消息后,我在此行收到标准调试错误:

static __inline errno_t __CRTDECL localtime_s(struct tm * _Tm, const time_t * _Time)
{
    return _localtime64_s(_Tm, _Time);
}

这基本上是在Calendar:Initialize()中调用 *localtime_s(localTime, &now);* 的结果 我可以使用此功能的弃用版本吗?我知道还有其他函数可以获取本地时间,但我不知道哪个是“正确的”。其他人向我建议我不应该使用“本地时间”,但似乎 localtime_s 也不起作用。

4

4 回答 4

5

请参阅文档

参数

_Tm值

指向要填写的时间结构的指针。

这意味着该函数期望第一个参数是指向有效tm实例的非空指针。

改变

tm *localTime = null;
localtime_s(localTime, &now);

tm localTime;
localtime_s(&localTime, &now);
于 2013-02-25T07:10:36.497 回答
2

localtime_s函数需要一个分配的struct tm指针,而您向它传递一个空指针。

使用例如

tm localTime:
localtime_s(&localTime, &now);
于 2013-02-25T07:11:08.637 回答
1

哈!

#include <iostream>
#include <fstream>
#include <ctime>
//#include <string>
//#include <cstring>
//#include <sstream>
using namespace std;

int main ()
{

    int LocalSeconds, LocalMinutes,  LocalHours, LocalDays, LocalMonths, LocalYears,
        DaysSinceSunday, DaysSinceJanuaryFirst, HoursDaylightSavings;

    time_t now = time(0);
        tm localTime;
    now = time(NULL); 
    localtime_s(&localTime, &now);


    LocalSeconds = (&localTime)->tm_sec;
    LocalMinutes = (&localTime)->tm_min;
    LocalHours = (&localTime)->tm_hour;
    LocalDays = (&localTime)->tm_mday;
    LocalMonths = (&localTime)->tm_mon;
    LocalYears = (&localTime)->tm_year;
    DaysSinceSunday = (&localTime)->tm_wday;
    DaysSinceJanuaryFirst = (&localTime)->tm_yday;
    HoursDaylightSavings = (&localTime)->tm_isdst;

    cout << LocalSeconds << " " << LocalMinutes<< " " <<  LocalHours<< " " << LocalDays
        << " " << LocalMonths<< " " << LocalYears<< " " <<endl;

    return 0;

}
于 2013-06-05T00:21:58.530 回答
1

最近碰巧在处理同样的问题。为了避免编译器错误/警告,我建议如下:

tm *localTime = new tm();
localtime_s(localTime, &now);

如果您不初始化localTime,您将收到“错误 C4700:使用未初始化的局部变量 'localTime'”

于 2016-03-30T19:44:13.397 回答