c-使用sprintf将字符串中的字符添加到其他字符串时出现意外输出



我有一个字符串,它是一个日期,格式为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);

但是我得到的输出是

日期是21122015

月是122015

年份是2015

也许这是一个愚蠢的问题,但我是C的新手。有人能解释一下原因吗?

根据C11标准,第7.21.6.6章,sprintf()函数,(emphasis mine

sprintf函数等效于fprintf,只是输出被写入数组(由参数s指定)而不是流写入一个空字符在所写字符的末尾[…]

这表明,在的情况下

sprintf(day, "%c%c", date[6], date[7]);

day应具有分配给3个char的最小空间,包括要写入的终止null。现在,在您的情况下,它没有终止null的空间,因此,sprintf()试图写入已分配的内存区域,调用未定义的行为。

在定义数组时,还需要考虑终止null的空间分配。

其他阵列也是如此。

相关内容

最新更新