【问题标题】:pointer to struct tm variable, cannot give back the changes指向 struct tm 变量的指针,无法返回更改
【发布时间】:2016-09-01 13:47:52
【问题描述】:

我有一个简单函数的问题(我猜是因为一些错误的指针分配)。由于strptime 函数(一个接受字符串并返回带有所有数据集的struct tm 的函数)在 Windows 中不存在,我通过调用其他基本工作函数创建了一种 strptime 函数。

这是测试代码。在 STRPTIME 函数中,时间设置得很好,而在 main 中我丢失了信息。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

void STRPTIME(char *strtm, struct tm *tminfo)
{
    time_t rawtime;
    int day, month, year;

    sscanf(strtm, "%d-%d-%d\n", &year, &month, &day);
    time( &rawtime );
    tminfo = localtime( &rawtime );
    tminfo->tm_year = year - 1900;
    tminfo->tm_mon  = month - 1;
    tminfo->tm_mday = day;

    mktime(tminfo);
    printf("date %d-%d-%d\n", tminfo->tm_year, tminfo->tm_mon, tminfo->tm_mday);
}

int main()
{
    char stm[11];
    struct tm tminfo;

    strcpy(stm, "2015-12-31");
    STRPTIME(stm, &tminfo);

    printf("tminfo %d-%d-%d\n", tminfo.tm_year, tminfo.tm_mon, tminfo.tm_mday);

    return(0);
}

【问题讨论】:

    标签: c pointers time struct strptime


    【解决方案1】:

    问题是您正在覆盖 tminfo 参数的指针。

    tminfo = localtime( &rawtime );
    

    函数参数就像一个局部变量:你可以覆盖它。它存在于堆栈中。但是您的来电者不会注意到这种变化。

    你需要做这样的事情:

    // Store the result in a temporary variable.
    struct tm * tmp = localtime( &rawtime );
    if ( tmp && tminfo ) {
        // Copy to caller's memory.
        memcpy( tminfo, tmp, sizeof( *tmp ) );
    }
    

    【讨论】:

    • 你说得对!!我没想到! if 是一个检查,以确保本地时间不会返回 NULL 并且输入也是 NULL,对吧?
    • 顺便说一句,这个解决方案是克服 strptime 问题的好方法,还是有更好的方法,最重要的是更快?
    • 是的,if 确保localtime 的结果和函数的参数都不是NULL,因为memcpy 的两个参数不能是NULL。由于您的 strptime 版本没有 format 参数,因此它并不是真正等效的。因此,它是否“足够好”可能取决于您的用例。另请参阅this question
    • 是的,我只有一个format,事实上我正在尝试按照其中一个人的建议去做。再次感谢!
    猜你喜欢
    • 2018-08-19
    • 2010-11-16
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    相关资源
    最近更新 更多