Search code examples
cpointerstimestructstrptime

pointer to struct tm variable, cannot give back the changes


I have an issue with a simple function (I guess because of some wrong pointer assigment). As strptime function (a function that takes a string and gives back a struct tm with all the data set) is not present in Windows, I created a sort of strptime function by calling other base working functions.

Here's the test code. Inside the STRPTIME function, time is well set, while then in main I lose the info.

#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);
}

Solution

  • The problem is that you're overwriting the pointer of your tminfo argument.

    tminfo = localtime( &rawtime );
    

    A function argument is like a local variable: you can overwrite it. It lives on the stack. But your caller will not notice this change.

    You need to do something like this:

    // 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 ) );
    }