我是 C 编程的初学者,尝试使用系统日期通过 C 代码获取昨天的日期,并附加在字符串“yesterdayDate_dt”中,就像昨天Date_dtmmddyy 一样,但面临运行时错误“总线错误 10”。
我的代码如下
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
int main(void)
{
time_t now = time(NULL);
struct tm *t = localtime(&now);
int dInt = t->tm_mday+1;
int mInt = t->tm_mon -1;
int yInt = t->tm_year+1900;
char *date= "23";
char *month = "01";
char *year = "13";
sprintf(date, "%d", dInt);
sprintf(month, "%d", mInt);
char *yestDt = (char *)malloc(strlen(date)+strlen(month)+strlen(year)+1);
strcpy(str,month);
strcat(str,date);
strcat(str,year);
printf("str:%s",yestDt);
return 0;
}
请查看 sprintf 文档并尝试以下代码
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
int main(void)
{
char yestDt[23];
time_t now = time(NULL);
now = now - (24*60*60);
struct tm *t = localtime(&now);
sprintf(yestDt,"yesterdayDate_dt%02d%02d%02d", t->tm_mon+1, t->tm_mday, t->tm_year - 100);
printf("Target String: \"%s\"", yestDt);
return 0;
}
此代码不合法:
sprintf(date, "%d", dInt);
sprintf
期望第一个参数指向可写字符存储。 date
未指向可写存储。
尝试将
date
的声明更改为可写的字符数组:
char date[3];
我现在不想摆弄,而是使用 tm* 和 time_t 的克隆。
//***Variables for Time***
tm* timeinfo;
tm* yesterdaytimeinfo;
time_t now;
time_t yesterdaynow;
static char charbuff[120]; //Char buffer for many functions
//*** In program ***
yesterdaynow = now - 86400;
yesterdaytimeinfo = localtime(&yesterdaynow);
strftime(charbuff, 30, "%x ", yesterdaytimeinfo);
println;
print(charbuff);