2016-05-06 66 views
0

我有一個簡單的函數(我猜是因爲某些錯誤的指針分配)的問題。由於strptime函數(一個函數接受一個字符串並返回一個帶有所有數據集的struct tm)在Windows中不存在,我通過調用其他基本工作函數創建了一種strptime函數。指向結構tm變量的指針,不能回覆更改

以下是測試代碼。在STRPTIME功能裏面,時間設定的很好,然後主要我失去了信息。

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <time.h> 

void STRPTIME(char *strtm, struct tm *tminfo) 
{ 
    time_t rawtime; 
    int day, month, year; 

    sscanf(strtm, "%d-%d-%d\n", &year, &month, &day); 
    time(&rawtime); 
    tminfo = localtime(&rawtime); 
    tminfo->tm_year = year - 1900; 
    tminfo->tm_mon = month - 1; 
    tminfo->tm_mday = day; 

    mktime(tminfo); 
    printf("date %d-%d-%d\n", tminfo->tm_year, tminfo->tm_mon, tminfo->tm_mday); 
} 

int main() 
{ 
    char stm[11]; 
    struct tm tminfo; 

    strcpy(stm, "2015-12-31"); 
    STRPTIME(stm, &tminfo); 

    printf("tminfo %d-%d-%d\n", tminfo.tm_year, tminfo.tm_mon, tminfo.tm_mday); 

    return(0); 
} 

回答

0

問題是您正在覆蓋您的參數tminfo參數的指針。

tminfo = localtime(&rawtime); 

函數參數就像一個局部變量:你可以覆蓋它。它住在堆棧上。但你的來電者不會注意到這個變化。

你需要做這樣的事情:

// Store the result in a temporary variable. 
struct tm * tmp = localtime(&rawtime); 
if (tmp && tminfo) { 
    // Copy to caller's memory. 
    memcpy(tminfo, tmp, sizeof(*tmp)); 
} 
+0

你是完全正確的!我沒有想到它! 'if'是一個檢查,以確保本地時間返回不是'NULL',並且輸入是'NULL',對吧? – Stefano

+0

順便說一句,這個解決方案是否是一個很好的解決問題的方法,或者有更有趣的方法,最重要的是更快? – Stefano

+1

是的,'if'確保'localtime'的結果和函數的參數不是'NULL',因爲'memcpy'的兩個參數不能是'NULL'。由於你的'strptime'版本沒有'format'參數,所以它並不是真的等價。所以它是否「足夠好」可能取決於你的用例。另見[這個問題](http://stackoverflow.com/questions/321849/strptime-equivalent-on-windows)。 – DarkDust