gpt4 book ai didi

c - printf() 的字符串宽度对于未终止的字符串是否安全?

转载 作者:太空狗 更新时间:2023-10-29 15:15:54 26 4
gpt4 key购买 nike

下面的定义是否明确?

const char not_a_c_string[] = { 'h', 'e', 'l', 'l', 'o' };
printf( "%.5s", (const char*) not_a_c_string );

这是一个关于特定形式 "%.5s" 的问题,而不是一个如何打印可能不以 NUL 结尾的字符串?,因为这个问题有 already been answered here建议使用 "%.*s" 结构。

最佳答案

首先,我相信您是想问精度,而不是字段宽度。所以,你的例子看起来像

 printf( "%.5s", (const char*) not_a_c_string );  //precision

代替

 printf( "%5s", (const char*) not_a_c_string );   //field width.

考虑到上述方法,不,在您的示例中它不会是 UB。

引用 C11 标准,章节 §7.21.6.1,fprintf 函数,第 8 段,(强调我的)

s               If no l length modifier is present, the argument shall be a pointer to the initial element of an array of character type.(280) Characters from the array are written up to (but not including) the terminating null character. If the precision is specified, no more than that many bytes are written. If the precision is not specified or is greater than the size of the array, the array shall contain a null character.

因此,只有在以下情况下,您才需要一个空分隔数组(字符串)

  • 缺少精度
  • 提供的精度是 > 提供的 char 数组的大小。

在您的情况下,提到的精度 (5) 不大于数组的大小(也是 5)。所以,没关系。


FWIW,如果示例仍然存在

 printf( "%5s", (const char*) not_a_c_string );

那么它将是 UB,因为你会在那里失去精度。

关于c - printf() 的字符串宽度对于未终止的字符串是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34749278/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com