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

标签 c arrays printf loadrunner

我有一个日期字符串,格式为 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 to fprintf, except that the output is written into an array (specified by the argument s) 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/

相关文章:

c++ - 绘图区 : fill area outside a region

javascript - 数组未正确填充日期

string - 如何在 awk 表达式中使用变量

c - 如何使用C发出警报声?

我可以通过线程进入应用程序来测量 Linux 中的 CPU 使用率吗

javascript - JavaScript 中的变异对象

java - 在实例化列表的变量中使用时,主列表值会发生变化

bash - 我如何让 $(/bin/printf -6) 返回 -6 而不是认为 -6 是一个选项

c - 需要c编程方面的帮助

c - select() 不等待