After assigning a value to the local2 pointer, the previously assigned value of the local pointer local2 overwritten.


Please explain the nature of this rewrite.


The task:

Create a function that calculates the time interval between two time stamps as a number of hours, minutes and seconds. The time stamps of the function should be obtained through the parameters of the structure type, and the result should be returned as the value of the structure variable.

 #include <stdio.h> #include <time.h> // описание функции struct tm timegap(struct tm * lc1, struct tm * lc2) { struct tm res; res = *lc2; res.tm_hour = lc1->tm_hour - lc2->tm_hour; res.tm_min = lc1->tm_min - lc2->tm_min; res.tm_sec = (lc1->tm_sec) - (lc2->tm_sec); return res; } void main () { // объявление переменных time_t crt_time; struct tm *local,*local2,result; // отметка времени getch(); crt_time = time(NULL); local = localtime(&crt_time); printf("%s\n",asctime(local)); // отметка времени №2 getch(); crt_time = time(NULL); local2 = localtime(&crt_time); //в этом месте наглядно виден факт перезаписи printf("%s\n",asctime(local2)); printf("%s\n",asctime(local)); // функции выводят одинаковые значения /* result = timegap(local2,local); printf("%s\n",asctime(&result)); */ } 
  • Most likely the fact is that you don’t give the value of the variable, but by reference. What happens if you replace localtime(&crt_time) with localtime(crt_time) ? - Nikolaj Sarry
  • one
    @NikolajSarry there is no link. This is taking the address. And the language is generally C, where links have never been seen. - αλεχολυτ

2 answers 2

The problem is that the result localtime is a pointer to an object that is internal to the language implementation, and can be changed by other function calls:

It may be altered that it’s possible

If you want to save the value, then you should save not the pointer, but the value:

 struct tm local = *localtime(&crt_time); 

    From MSDN

    Both the 32-bit and the 64-bit versions of the gmtime , mktime , mkgmtime , and the structure. Each call to one of these routines.

    What does it mean in translation?

    Both 32 and 64 bit versions of the gmtime , mktime , mkgmtime , and localtime functions use one tm structure per stream to convert. Each call to one of these functions destroys the result obtained in the previous call.