我有以下代码。
#include<time.h>
#include<stdio.h>
int main(int argc, char** argv) {
time_t t1, t2;
time(&t1);/* set current time to t1 */
struct tm T1, T2;
int i;
scanf("%d", &i); /* for delaying */
time(&t2); /* set current time to t2 */
T1 = *(struct tm*)localtime(&t1);
T2 = *(struct tm*)localtime(&t2);
printf("%s%s", asctime(&T1), asctime(&T2)); /* display them */
}
基本上,我想获得 t1 上的当前时间,然后(在等待 i 被读取造成的延迟之后)t2 上的当前时间。t1 和 t2 不同,T1.tm_sec 和 T2.tm_sec 也不同,但 printf 显示的日期完全相同(对应于 T1 的日期)。我知道在内部,asctime(http://www.cplusplus.com/reference/ctime/asctime/?kw=asctime)使用静态指针,但我尝试了一个较小的示例程序,其函数返回一个静态字符指针,他们工作。
char* test(int t) {
static char result[10];
sprintf(result, "%d", t);
return result;
}
我像这样使用它
printf("%s ", test(5));
printf("%s ", test(7));
它有效(打印的字符串不同)。
所以我想它不可能来自那里。我还复制了 asctime 代码(来自 cplusplus)并将一些 printfs 放入函数中,我注意到结果变量在 sprintf 语句之后得到正确更新。
那么 printf 显示相同的日期会发生什么?
来自 cplusplus.com 的 asctime 代码
char* asctime(const struct tm *timeptr)
{
static const char wday_name[][4] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
static const char mon_name[][4] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
static char result[26];
sprintf(result, "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n",
wday_name[timeptr->tm_wday],
mon_name[timeptr->tm_mon],
timeptr->tm_mday, timeptr->tm_hour,
timeptr->tm_min, timeptr->tm_sec,
1900 + timeptr->tm_year);
return result;
}