使用 C 打印系统时间时出现意外输出

Unexpected output while printing system time using C

我一直在编写代码,使用 time.h 头文件打印当前系统日期和时间,但得到了意外的输出。注意:此摘录是更大 system.I 的一部分,已简化代码以指出错误部分。

#include<stdio.h>
#include<time.h>
typedef struct dater
{
    int date;
    int month;
    int year;
}DATER;

typedef struct timer
{
    int hour;
    int min;
    int sec;
}TIMER;

DATER * current_date()
{
    DATER * d;
    time_t currentTime;
    time(&currentTime);
    struct tm *myTime=localtime(&currentTime);
    d->date=myTime->tm_mday;
    d->month=myTime->tm_mon+1;
    d->year=myTime->tm_year+1900;
    return d;
}

TIMER * current_time()
{
    TIMER * t;
    time_t currentTime;
    time(&currentTime);
    struct tm *myTime=localtime(&currentTime);
    t->hour=myTime->tm_hour;
    t->min=myTime->tm_min;
    t->sec=myTime->tm_sec;
    return t;
}
int main()
{
    DATER * d=current_date();
    TIMER * t=current_time();

    printf("Today's Date Is: %02d.%02d.%d\n",d->date,d->month,d->year);
    printf("TIme Is: %02d:%02d:%02d",t->hour,t->min,t->sec);

    return 1;
}

输出结果如下:

Today's Date Is: 17.39.17
Time Is: 39:17:17

如果我在 current_time() 函数调用之前添加语句 printf("Today's Date Is: %02d.%02d.%d\n",d->date,d->month,d->year);,问题似乎得到解决。

我不太理解为什么会发生这种情况,因为我在两个不同的实例中将日期和时间存储在两个不同的结构中。

PS- 我知道这是一个精心设计的 method.But 正如我之前提到的,我正在一个更大的项目中使用它

你真的应该打开警告。

$ gcc k.c -Wall -Wextra
k.c: In function ‘current_date’:
k.c:23:12: warning: ‘d’ is used uninitialized in this function [-Wuninitialized]
   23 |     d->date=myTime->tm_mday;
      |     ~~~~~~~^~~~~~~~~~~~~~~~
k.c: In function ‘current_time’:
k.c:35:12: warning: ‘t’ is used uninitialized in this function [-Wuninitialized]
   35 |     t->hour=myTime->tm_hour;
      |     ~~~~~~~^~~~~~~~~~~~~~~~

您还没有分配任何内存。 d 只是一个未初始化的指针。将函数更改为 return 结构或先分配内存。

DATER * current_date()
{
    DATER *d = malloc(sizeof *d);

DATER current_date()
{
    DATER d;
    time_t currentTime;
    time(&currentTime);
    struct tm *myTime=localtime(&currentTime);
    d.date=myTime->tm_mday;
    d.month=myTime->tm_mon+1;
    d.year=myTime->tm_year+1900;
    return d;
}

我真的有点惊讶你的代码没有崩溃。这是更有可能的情况。