问题描述
以下定义是否明确?
const char not_a_c_string[] = { 'h', 'e', 'l', 'l', 'o' };
printf( "%.5s", (const char*) not_a_c_string );
这是关于特定格式"%.5s"
的问题,而不是如何打印可能不是NUL终止的字符串?,因为此问题具有,其中建议使用"%.*s"
构造.
This is a question about the specific form "%.5s"
, and not an how to print a possibly not NUL-terminated string? as this question has already been answered here where the "%.*s"
construct is suggested.
推荐答案
首先,我认为,您要问的是精度,而不是字段宽度 .因此,您的示例看起来像
First of all, I believe, you meant to ask about the precision, not the field width. So, your example is to look like
printf( "%.5s", (const char*) not_a_c_string ); //precision
代替
printf( "%5s", (const char*) not_a_c_string ); //field width.
考虑到上述方法,不,在您的示例中它将不是UB.
Considering the above approach, no, it will not be UB in your example.
要引用C11
标准,请参见第§7.21.6.1章 fprintf
函数,第8段,(强调我的)
To quote the C11
standard, chapter §7.21.6.1, The fprintf
function, paragraph 8, (emphasis mine)
因此,只有当您是其中一个时,才需要使用以空值分隔的数组( string )
So, you need to have a null delimited array (string) only if you're either
- 缺少精度
- 提供的精度为
>
所提供的char
数组的大小.
- missing the precision
- supplied precision is
>
the size of the suppliedchar
array.
在您的情况下,提到的精度(5)不大于数组的大小(也为5).所以,很好.
In your case, the mentioned precision (5) is not greater that the size of the array (also 5). So, It's fine.
FWIW,如果示例仍然存在
FWIW, if the example remains
printf( "%5s", (const char*) not_a_c_string );
那么它将是UB,因为您在那里会失去精度.
then it will be UB, as you'll be missing precision there.
这篇关于使用未终止的字符串,printf()的字符串宽度安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!