我有一个日期字符串,格式为 yyyymmdd。我需要找出日、月、年并将它们存储在单独的字符串中并进一步使用它们。 我写了下面的代码
char *date="20151221";
char day[2];
char month[2];
char year[4];
sprintf(day, "%c%c", date[6], date[7]);
sprintf(month, "%c%c", date[4], date[5]);
sprintf(year, "%c%c%c%c", date[0], date[1],date[2],date[3]);
lr_output_message("day is %s",day);
lr_output_message("month is %s",month);
lr_output_message("year is %s",year);
但是得到的输出是
day is 21122015
month is 122015
year is 2015
也许这是一个愚蠢的问题,但我是 C 语言的新手。任何人都可以解释一下原因吗?
最佳答案
根据 C11
标准,章节 §7.21.6.6,sprintf()
函数,(强调我的)
The
sprintf
function is equivalent tofprintf
, except that the output is written into an array (specified by the arguments
) rather than to a stream. A null character is written at the end of the characters written; [...]
表示,如果是
sprintf(day, "%c%c", date[6], date[7]);
day
应为 3 个 char
分配最小空间,包括要写入的终止 null。现在,在您的情况下,它没有终止 null 的空间,因此 sprintf()
尝试写入过去分配的内存区域,调用 undefined behavior .
在定义数组时,您还需要考虑终止空值的空间分配。
其他数组也一样。
关于c - 使用 sprintf 将字符串中的字符添加到其他字符串时出现意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34428108/