【问题标题】:Unexpected output while printing system time using C使用 C 打印系统时间时出现意外输出
【发布时间】:2020-09-22 03:14:54
【问题描述】:

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

#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

如果我将声明 printf("Today's Date Is: %02d.%02d.%d\n",d-&gt;date,d-&gt;month,d-&gt;year); 放在 current_time() 函数调用之前,问题似乎得到了解决。

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

PS- 我知道这是一个复杂的方法。但是正如我之前提到的,我在一个更大的项目中使用它

【问题讨论】:

  • 你说输出出乎意料。你期望的输出是什么?
  • 你的指针没有指向有效的地方
  • 您在没有初始化指针的情况下写入DATER * d;。您还必须注意不要返回局部变量的地址——让它成为一个参数并让用户提供内存。
  • 在未初始化的情况下使用dt 时不会收到警告吗?
  • 您可以返回结构的副本而不是指针。

标签: c pointers time time.h


【解决方案1】:

你真的应该打开警告。

$ 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 只是一个未初始化的指针。要么更改函数以返回结构,要么先分配内存。

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;
}

实际上我有点惊讶您的代码没有崩溃。这种情况更有可能发生。

【讨论】:

  • 是的,我在这里发布后一分钟后想通了。感谢您的帮助。
  • 你也可以提出-Werror,代码还没有编译。
猜你喜欢
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 2021-10-12
  • 2022-01-10
相关资源
最近更新 更多