我是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;
}
答案 0 :(得分:4)
请查看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;
}
答案 1 :(得分:0)
此代码不合法:
sprintf(date, "%d", dInt);
sprintf
期望第一个参数指向可写字符存储。 date
未指向可写存储。
尝试将date
的声明更改为可写的字符数组:
char date[3];