簡體   English   中英

C程序time_t和struct tm,結果相同嗎?

[英]C program time_t and struct tm, same result?

我是C程序的新手,使用mktime函數編寫程序時遇到了一些問題。

我聲明2時間,第一個是系統時間,第二個是系統時間之前1天,這是我的代碼:

struct tm *now = calloc(1,sizeof(struct tm));
struct tm *dayb4 = calloc(1,sizeof(struct tm));
time_t t1 = time(NULL);

now = localtime(&t1);
dayb4 = localtime(&t1);

dayb4->tm_day -= 1;
mktime(dayb4);

但是,我發現“現在”和“ dayb4”的時間相同,也就是當前時間的前一天。有人可以告訴我我錯了哪一部分嗎?

非常感謝 !!!

當您更新localtime()返回值時,會出現問題,您需要使用localtime_r()

struct tm *localtime(const time_t *timep);

localtime()的返回值指向靜態分配的結構,該結構可能被隨后對任何日期和時間函數的調用所覆蓋。

struct tm *localtime_r(const time_t *timep, struct tm *result);

localtime_r()將數據存儲在用戶提供的結構中。

在您的示例中,它應該類似於:

dayb4 = localtime_r(&t1, dayb4);

您可以執行以下操作來代替calloc和重疊結構:

struct tm now;
struct tm dayb4;
time_t t1 = time(NULL);

now = *localtime(&t1);
dayb4 = *localtime(&t1);

dayb4.tm_day -= 1;
mktime(&dayb4);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM