How to get the current time and write it to an array of strings? using this code, each element of the array will point to the same time, but it is necessary that the time be different. 1st element 19:44, 2nd element -19: 45, etc.

#include <time.h> #include <stdio.h> #include <conio.h> int main(void) { struct tm *ptr; time_t lt; lt = time(NULL); ptr = localtime(&lt); printf(asctime(ptr)); getch(); return 0; } 
  • Explain how the current time may be slightly different values? And in which array you need to write these values, in your code there is nothing like that. - PinkTux

2 answers 2

 #include < stdio.h > // Для printf #include < time.h > // Для time, ctime int main (void) { // Переменная для сохранения текущего времени long int ttime; // Считываем текущее время ttime = time (NULL); // С помощью функции ctime преобразуем считанное время в // локальное, а затем в строку и выводим в консоль. printf (“Время: %s\n”,ctime (&ttime) ); return 0; } 

    According to the specification , the asctime() function returns a pointer to a static string, which is overwritten with each function call. So, if you want to save the values ​​obtained, you need to copy them somewhere. For example:

     struct tm *ptr; time_t lt; char *data[2]; lt = time(NULL); ptr = localtime(&lt); data[0] = strdup( asctime(ptr) ); sleep(10); lt = time(NULL); ptr = localtime(&lt); data[1] = strdup( asctime(ptr) ); printf( "%s\n%s\n", data[0], data[1] ); free( data[0] ); free( data[1] ); 

    In POSIX and BSD also the asctime_r() function, which takes a pointer to a string to be stored, the length of which must be at least 26 bytes. With this in mind, you can:

     struct tm *ptr; time_t lt; char data[2][26]; lt = time(NULL); ptr = localtime(&lt); asctime_r(ptr, data[0]); sleep(10); lt = time(NULL); ptr = localtime(&lt); asctime_r(ptr, data[1]); printf( "%s\n%s\n", data[0], data[1] ); 

    The same applies to the shorter version in the answer @AlexUlianov, there is ctime() , and there is also ctime_r() .