这是我的代码:
time_t tim=time(NULL); // acquire time information
struct tm * now=localtime(&tim);
char cyear[3], cmonth[2], cday[2], chour[2], cmin[2];
int test = 13;
sprintf(cyear, "%d", test);
sprintf(cmonth, "%d", now->tm_mon+1);
sprintf(cday, "%d", now->tm_mday);
sprintf(chour, "%d", now->tm_hour);
sprintf(cmin, "%d", now->tm_min);
printf("cyear is: %s\n",cyear);
printf("cmin is: %s\n",cmin);
我得到的输出是:
cyear is:
cmin is: 7
输出也不适用于 cmonth 或 cday,但 chour 和 cmin 似乎提供了正确的输出。这是怎么回事?
最佳答案
cmonth
版本如果是十月、十一月或十二月,将导致缓冲区溢出。 cday
如果是当月的 10 号或更晚会缓冲区溢出,chour
如果过了十点就会溢出,cmin
如果是整点过 10 分钟,将会溢出。
所以您的代码适用于 1 January 1970 00:00,但其他情况不多!
要解决这个问题,请增大缓冲区;并使用 snprintf
函数。如果字段不包含您期望的内容,这将保证您不会发生缓冲区溢出。例如:
char chour[6];
snprintf(chour, sizeof chour, "%d", now->tm_hour);
关于c - 为什么 sprintf 在一个例子中起作用,而在下一个例子中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26706422/