Pregunta

I am new to C program and I got a some problem when I code the program using mktime function.

I declare 2 time, first one is system time, and the second one is 1 day before it, here is my code:

struct tm *now = calloc(1,sizeof(struct tm));
struct tm *dayb4 = calloc(1,sizeof(struct tm));
time_t t1 = time(NULL);

now = localtime(&t1);
dayb4 = localtime(&t1);

dayb4->tm_day -= 1;
mktime(dayb4);

However, I found the the time "now" and "dayb4" are the same, which is 1 day before current time... Could anyone told me which part I getting wrong?

Thank a lot !!!

¿Fue útil?

Solución

The problem arise when you update localtime() return value, you need to use localtime_r():

struct tm *localtime(const time_t *timep);

The return value of localtime() points to a statically allocated struct which might be overwritten by subsequent calls to any of the date and time functions.

struct tm *localtime_r(const time_t *timep, struct tm *result);

The localtime_r() stores the data in a user-supplied struct.

In your example, it should be something similar to:

dayb4 = localtime_r(&t1, dayb4);

Otros consejos

Instead of calloc and overlapping structures, you could do the following:

struct tm now;
struct tm dayb4;
time_t t1 = time(NULL);

now = *localtime(&t1);
dayb4 = *localtime(&t1);

dayb4.tm_day -= 1;
mktime(&dayb4);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top