Duc*_*yen 4 c struct pointers time-t
所以我需要专门使用struct tm来打印我的生日,我成功了.但是,我还需要使用strftime()以不同的格式打印它.这就是我遇到问题的地方,因为strftime()只识别指针参数.
#include <stdio.h>
#include <time.h>
int main(){
struct tm str_bday;
time_t time_bday;
char buffer[15];
str_bday.tm_year = 1994 - 1900 ;
str_bday.tm_mon = 7 - 1;
str_bday.tm_mday = 30;
str_bday.tm_hour = 12;
str_bday.tm_min = 53;
time_bday = mktime(&str_bday);
if(time_bday == (time_t)-1)
fprintf(stdout,"error\n");
else
{
fprintf(stdout,"My birthday in second is: %ld \n",time_bday);
fprintf(stdout,"My birthday is: %s\n", ctime(&time_bday));//Wed July 22 12:53:00 1998
strftime(buffer,15,"%d/%m/%Y",time_bday);
fprintf(stdout,"My birthday in D/M/Y format is %s",buffer);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
错误是:
Error: passing argument 4 of ‘strftime’ makes pointer from integer without a cast
expected ‘const struct tm * restrict’ but argument is of type ‘time_t’
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我如何解决它?
编辑:将time_bday更改为&str_bday有效!但现在程序每次运行时都会输出随机时间和日期.
编辑:而不是strftime()之后的fprintf(),我使用了puts(缓冲区),它运行得很好.此外,将缓冲区[15]更改为缓冲区[30],因为我有小时,分钟和秒.
通过查看strftime原型,你可以看到你应该传递一个const struct tm*最后一个参数:
size_t strftime(char *s, size_t maxsize, const char *format, const struct tm *timeptr);
Run Code Online (Sandbox Code Playgroud)
这将&str_bday取代time_bday你的情况.
struct tm有几个字段你没有初始化,因此采取不确定的值,导致你看到的时间跳跃.struct tm str_bday = {0}在插入值之前,可以使用,将所有字段初始化为零.