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(<); data[0] = strdup( asctime(ptr) ); sleep(10); lt = time(NULL); ptr = localtime(<); 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(<); asctime_r(ptr, data[0]); sleep(10); lt = time(NULL); ptr = localtime(<); 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() .