cmktime

mktime() overwrite time_t in C


I have a problem with mktime in c:

time_t t_fim;
time(&t_fim);

struct tm* p_fim;
struct tm* c_fim;
p_fim = localtime(&t_fim);
c_fim = localtime(&t_fim);

......

p_fim->tm_year = ano-1900;
p_fim->tm_mon = mes-1;
p_fim->tm_mday = dia;
//here the p_fim date is good

c_fim->tm_mday -=47;
mktime(c_fim);

printf("Pascoa %d %d %d\n", p_fim->tm_mday, p_fim->tm_mon + 1, p_fim->tm_year + 1900);
printf("Carnaval %d %d %d\n", c_fim->tm_mday, c_fim->tm_mon+1, c_fim->tm_year + 1900);

//here the c_fim is good with -47 days but the `p_fim` is now equal with `c_fim`

The mktime is changing the value of p_fim, how to solve that?


Solution

  • Try getting rid of the pointers

    struct tm p_fim;
    struct tm c_fim;
    p_fim = *localtime(&t_fim);
    c_fim = *localtime(&t_fim);
    

    Or, if you're on a POSIX system, try localtime_r() instead