小心C語言時間函數陷阱

`1 #include <stdio.h>2 #include <time.h>34 int main ()5 {67 time_t time_1, time_2;8 struct tm *tm_1, *tm_2, *tm_3;9 struct tm tm_4, tm_5;1011 printf("-------------------- PART I -------------------\n");1213 time_1 = time(NULL);14 sleep(3);15 time_2 = time(NULL);16 printf("time1:%d time2:%d\n",time_1,time_2);1718 tm_1 = (struct tm*)localtime(&time_1);19 tm_2 = (struct tm*)localtime(&time_2);20 tm_3 = (struct tm*)localtime(&time_1);2122 printf("tm_1 ptr:%p tm_2 ptr:%p tm_3 ptr:%p\n",tm_1,tm_2,tm_3);23 printf("asctime(tm_1):%s",asctime(tm_1));24 printf("asctime(tm_2):%s",asctime(tm_2));25 printf("asctime(tm_3):%s",asctime(tm_3));26 }`

(1) 第22行，struct tm結構體 tm_1、tm_2 和tm_3的值有什麼關係？

(2) 第23-26行的輸出結果中，tm_2的時間真的比tm_1晚3秒嗎？

-------------------- PART I -------------------

time1:1340256774 time2:1340256777

tm_1 ptr:0xfec6f48 tm_2 ptr:0xfec6f48 tm_3 ptr:0xfec6f48

asctime(tm_1):Thu Jun 21 01:32:54 2012

asctime(tm_2):Thu Jun 21 01:32:54 2012

asctime(tm_3):Thu Jun 21 01:32:54 2012

`1 #include <stdio.h>2 #include <time.h>34 int main ()5 {67 time_t time_1, time_2;8 struct tm *tm_1, *tm_2, *tm_3;9 struct tm tm_4, tm_5;1011 printf("-------------------- PART I -------------------\n");1213 time_1 = time(NULL);14 sleep(3);15 time_2 = time(NULL);16 printf("time1:%d time2:%d\n",time_1,time_2);1718 tm_1 = (struct tm*)localtime(&time_1);19 tm_2 = (struct tm*)localtime(&time_2);20 tm_3 = (struct tm*)localtime(&time_1);2122 printf("tm_1 ptr:%p tm_2 ptr:%p tm_3 ptr:%p\n",tm_1,tm_2,tm_3);23 printf("asctime(tm_1):%s",asctime(tm_1));24 printf("asctime(tm_2):%s",asctime(tm_2));25 printf("asctime(tm_3):%s",asctime(tm_3));26 2728 printf("-------------------- PART II -------------------\n");2930 time_1 = time(NULL);31 sleep(3);32 time_2 = time(NULL);33 printf("time1:%d time2:%d\n",time_1,time_2);3435 tm_4 = *((struct tm*)localtime(&time_1));36 tm_5 = *((struct tm*)localtime(&time_2));3738 printf("tm_4 ptr:%p tm_5 ptr:%p\n",&tm_4,&tm_5);39 printf("tm_4 sec:%d tm_5 sec:%d\n",tm_4.tm_sec,tm_5.tm_sec);4041 printf("asctime(&tm_4):%sasctime(&tm_5):%s",asctime(&tm_4),asctime (&tm_5));42 printf("asctime(&tm_4) ptr:%p asctime(&tm_5) ptr:%p\n",asctime (&tm_4),asctime(&tm_5));4344 printf("asctime(&tm_4):%s",asctime(&tm_4));45 printf("asctime(&tm_5):%s",asctime(&tm_5));`

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD