10

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 is the problem with that? Is that it can't hold the moment that you capture it, will it always update ? If so, how can I capture the moment of time and it not update like that.

VirusPTIT
  • 115
  • 1
  • 8
  • Is that even valid C++? When did it become possible to initialize members of a struct like that? – Andon M. Coleman Nov 27 '16 at 15:18
  • 3
    @AndonM.Coleman Since C++11. You can have in-class member initialization. – vsoftco Nov 27 '16 at 15:19
  • like the answer bellow, that was my mistake, i shouldnt initialize a member with pointer like that in this case, – VirusPTIT Nov 27 '16 at 15:26
  • You can also use `std::chrono`: http://en.cppreference.com/w/cpp/chrono/time_point. Sometimes C++ makes your life simpler. If you want to do calculation with dates, I recommend Howard Hinnants great libraries: https://github.com/HowardHinnant/date – Jens Nov 28 '16 at 08:13

1 Answers1

18

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 initialize it with the dereferenced value of the returned pointer *localtime(&t).

Galik
  • 47,303
  • 4
  • 80
  • 117