Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

struct

time.h

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;
}
like image 925
witeseb Avatar asked Oct 17 '25 00:10

witeseb


1 Answers

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);
like image 130
dbush Avatar answered Oct 18 '25 14:10

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!