witeseb
witeseb

Reputation: 53

Can I use two tm struct from time.h in the same file?

I'm trying to do a book borrowing system witch can tell the user the day that they have to return the book. Because I have to use the data to check if the borrowing times are exceeding limit or not. I try to use two tm structures.

struct tm *Olddate;
struct tm *Newdate;

I added days to one of the structure like this

Newdate->tm_mday += 7;

When I tried to print out the two different struct, the output are somehow the same.

printf("Current local time and date: %s", asctime(Olddate));
printf("Current new time and date: %s", asctime(Newdate));

Output:

Current local time and date: Tue May 17 21:37:16 2022
New time and date: Tue May 17 21:37:16 2022

Minimal reproducible example:

#include <stdio.h>
#include <time.h>
int main () {
    time_t rawtime;

    struct tm *Olddate;
    struct tm *Newdate;

    time( &rawtime );

    Olddate = localtime(&rawtime);
    Newdate = localtime(&rawtime);
    
    Newdate->tm_mday += 7;

    printf("Current local time and date: %s", asctime(Olddate));
    printf("New time and date: %s", asctime(Newdate));
    return 0;
}

Upvotes: 4

Views: 312

Answers (1)

dbush
dbush

Reputation: 223739

The localtime function returns a pointer to static data, so the contents of that data can be overwritten an subsequent calls.

You should instead use localtime_r which accepts the address of a struct tm to populate.

time_t rawtime;

struct tm Olddate;
struct tm Newdate;

time( &rawtime );

localtime_r(&rawtime, &Olddate);
localtime_r(&rawtime, &Newdate);

Newdate.tm_mday += 7;

printf("Current local time and date: %s", asctime(&Olddate));
printf("New time and date: %s", asctime(&Newdate));

If you're using MSVC, use localtime_s instead.

localtime_s(&Olddate, &rawtime);
localtime_s(&Newdate, &rawtime);

Upvotes: 7

Related Questions