1

私はCプログラミングの初心者で、システム日付を使用してCコードを介して昨日の日付を取得しようとしており、このyesterdayDate_dtmmddyyのように文字列「yesterdayDate_dt」に追加しますが、実行時エラー「バスエラー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;
}
4

2 に答える 2

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;
}
于 2013-01-24T03:57:28.687 に答える
0

このコードは合法ではありません:

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

sprintfは、最初のパラメーターが書き込み可能な文字ストレージを指すことを想定しています。 date書き込み可能なストレージを指していません。

の宣言をdate書き込み可能な文字配列に変更してみてください。

char date[3];
于 2013-01-24T03:59:47.560 に答える