下面我有四个功能。first()
和second()
仅初始化结构tm
的年,月和日。first_p()
和second_p
使用malloc分配内存,然后分配年,月和日。所有功能最后都调用mktime()
。
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void first()
{
int year1 = 2020, month1 = 4, day1 = 23;
struct tm date1 = {.tm_year = year1-1900, .tm_mon = month1-1, .tm_mday = day1};
mktime(&date1);
printf("%s", asctime(&date1));
}
void second()
{
int year2 = 2021, month2 = 5, day2 = 24;
struct tm date2 = {.tm_year = year2-1900, .tm_mon = month2-1, .tm_mday = day2};
mktime(&date2);
printf("%s", asctime(&date2));
}
void first_p()
{
int year1 = 2020, month1 = 4, day1 = 23;
struct tm *date1 = (struct tm *) malloc (sizeof(struct tm));
date1->tm_year = year1 - 1900;
date1->tm_mon = month1 -1;
date1->tm_mday = day1;
mktime(date1);
printf("%s", asctime(date1));
}
void second_p()
{
int year2 = 2021, month2 = 5, day2 = 24;
struct tm *date2 = (struct tm *) malloc (sizeof(struct tm));
date2->tm_year = year2 - 1900;
date2->tm_mon = month2 - 1;
date2->tm_mday = day2;
mktime(date2);
printf("%s", asctime(date2));
}
[在main()
中调用这些函数时,我尝试了不同的置换:
first_p()
和second_p()
显示随机的日期和时间。 int main()
{
first();
second();
first_p();
second_p();
return 0;
}
Thu Apr 23 00:00:00 2020
Mon May 24 00:00:00 2021
Thu Sep 30 23:09:20 66488
Wed Aug 31 14:44:48 66489
second_p()
显示随机日期和时间。int main()
{
first_p();
second_p();
first();
second();
return 0;
}
Thu Apr 23 00:00:00 2020
Sun Dec 8 01:26:16 -103880
Thu Apr 23 00:00:00 2020
Mon May 24 00:00:00 2021
second_p()
显示随机日期和时间。int main()
{
first_p();
first();
second();
second_p();
return 0;
}
Thu Apr 23 00:00:00 2020
Thu Apr 23 00:00:00 2020
Mon May 24 00:00:00 2021
Thu Oct 9 04:53:52 60110
first_p()
和second_p()
显示随机日期和时间。int main()
{
first();
first_p();
second_p();
second();
return 0;
}
Thu Apr 23 00:00:00 2020
Sat Sep 25 12:05:36 182934
Fri Aug 26 03:41:04 182935
Mon May 24 00:00:00 2021
我观察到的是:
我是否错过了有关mktime()的某些行为?
[您在malloc()
数据中的小时,分钟,秒和夏时制标志中具有准随机(不确定的)值,因此从mktime()
中获得不确定的结果。
使用calloc()
代替malloc()
,或者自己将字段清零。