VirusPTIT VirusPTIT - 6 days ago 6
C++ Question

C++ struct tm & time_t

i have an array of time here:

struct cl{
unsigned char *buffer;
time_t t = time(0);
struct tm * ct = localtime(&t);
};


and then:

cl sadi[10];


but for example i got
sadi[5]
at
21:58
, and when i got a
sadi[6]
at
21:59

then i check again all my
sadi[].ct->tm_min
are
59
, what the problem with that? is that it cant hold the moment that u capture it, it always update ? and if so, how can i capture the moment of time and it not update like that

Answer

This line:

struct tm * ct = localtime(&t);

The problem is that the pointer that localtime(&t) returns is a static internal buffer. So it returns exactly the same pointer value (address) every time it is called. That means that all your array elements have pointers to the same struct tm object.

One solution is to make a copy of the data each time you call localtime:

struct cl {
    unsigned char* buffer;
    time_t t = time(0);  
    struct tm ct = *localtime(&t);
};

So now I declare struct tm ct; (not a pointer) and assign it the dereferenced value of the returned pointer *localtime(&t).

Comments