简体   繁体   中英

How to get yesterday's date from system date and append to string?

I am a beginner in C programming and trying to get the yesterday's date through c code using system date and append in the string "yesterdayDate_dt" like this yesterdayDate_dtmmddyy but facing run time error “bus error 10” .

My code as below

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

Please look into sprintf documentation and try the below code

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

This code is not legal:

sprintf(date, "%d", dInt);

sprintf expects the first parameter to point to writable character storage. date is not pointing to writable storage.

Try changing the declaration of date to a writable array of characters:

char date[3];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM