ctime的连续调用覆盖以前的值

本文探讨了ctime()函数在连续调用时可能导致的时间显示错误。通过一个示例程序展示了如何正确地展示不同时间点,避免静态缓冲区被覆盖的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



ctime() 的连续调用覆盖以前的值


随后调用 ctime() 函数重写前一次调用的结果。下面的代码示例演示了此行为通过打印相同时间的开始时间和完成其第一个的 printf () 调用中的时间。但是,应该不同的开始和结束时间。若要更正这种情况下,不要在一次调用 printf 两次调用 ctime完成时间则晚于开始时间,如预期的那样。

这是预期的行为。Ctime() 函数使用一个静态缓冲区来存储其结果。因此,当第二个 ctime() 调用 printf 函数中,ctime() 会覆盖第一个 ctime() 调用返回的值。


/*
 * Compile options needed: None
 */ 

#include <stdio.h>
#include <time.h>

time_t start, finish=0;

void main(void)
{

  //loop until 3 seconds pass
  for (time(&start); finish-start < 3; time(&finish))
  ;


  /* If the following statement is used, the start and finish
     display times do not differ, both parameters get a copy of
     the same buffer which is overwritten twice before entering
     printf: */ 

  printf("Start time was %s and ending time was %s", ctime(&start),
     ctime(&finish));

  /* If the following statements are used instead, the start and
     finish times are different, as expected: */ 

     printf("Start time was %s", ctime(&start));
     printf("and ending time was %s\n", ctime(&finish));
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值