为什么 strptime c 函数会改变结构?
Why strptime c-function changes the structure?
函数的不可理解行为 strptime()
:
#define _XOPEN_SOURCE
#include <stdio.h>
#include <time.h>
double getPeriod(char * dateStart, char * dateStop) {
struct tm tmStart, tmStop;
time_t timeStampStart, timeStampStop;
strptime(dateStart, "%Y-%m-%d %H:%M:%S", &tmStart);
strptime(dateStop, "%Y-%m-%d %H:%M:%S", &tmStop);
timeStampStart = mktime(&tmStart);
timeStampStop = mktime(&tmStop);
printf("%d\t%d\n", tmStart.tm_hour, tmStop.tm_hour);
}
int main()
{
getPeriod("2016-12-05 18:14:35", "2016-12-05 18:18:34");
return 0;
}
输出:
17 18
为什么会这样?
编译器 gcc (GCC) 6.2.1
OSLinux
tmStart
和tmStop
没有初始化,所以传给mktime
的时候有些字段会没有初始化。因此,该行为在技术上是未定义的。
来自 strptime
手册页(注意前两句):
In principle, this function does not initialize tm but only stores the values specified. This means that tm
should be initialized before the call. Details differ a bit between different UNIX systems. The glibc
implementation does not touch those fields which are not explicitly specified, except that it recomputes the tm_wday
and tm_yday
field if any of the year, month, or day elements changed.
函数的不可理解行为 strptime()
:
#define _XOPEN_SOURCE
#include <stdio.h>
#include <time.h>
double getPeriod(char * dateStart, char * dateStop) {
struct tm tmStart, tmStop;
time_t timeStampStart, timeStampStop;
strptime(dateStart, "%Y-%m-%d %H:%M:%S", &tmStart);
strptime(dateStop, "%Y-%m-%d %H:%M:%S", &tmStop);
timeStampStart = mktime(&tmStart);
timeStampStop = mktime(&tmStop);
printf("%d\t%d\n", tmStart.tm_hour, tmStop.tm_hour);
}
int main()
{
getPeriod("2016-12-05 18:14:35", "2016-12-05 18:18:34");
return 0;
}
输出:
17 18
为什么会这样?
编译器 gcc (GCC) 6.2.1 OSLinux
tmStart
和tmStop
没有初始化,所以传给mktime
的时候有些字段会没有初始化。因此,该行为在技术上是未定义的。
来自 strptime
手册页(注意前两句):
In principle, this function does not initialize tm but only stores the values specified. This means that
tm
should be initialized before the call. Details differ a bit between different UNIX systems. Theglibc
implementation does not touch those fields which are not explicitly specified, except that it recomputes thetm_wday
andtm_yday
field if any of the year, month, or day elements changed.