gpt4 book ai didi

c - 固定字符串的 printf 格式是什么?

转载 作者:行者123 更新时间:2023-12-02 06:56:14 24 4
gpt4 key购买 nike

这是安全的还是 UB 的?

char x[5] = { 'a', 'b', 'c', 'd', 'e' };
printf("%5.5s\n", x);

打印非零终止字符串的正确 printf 格式是什么? (或者打印 c 字符串的前 N ​​个字符的格式是什么?)

最佳答案

行为定义明确。对应于普通 %s 转换说明符的参数必须是指向 string 的指针(这意味着,根据定义,它包含一个空的 '\0' 终止符),但如果指定了精度,则参数不必是指向字符串的指针(即,只要数组足够长,就没有空终止符)。

引用C11标准草案,N1570 7.21.6.1p8:

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.

如果要打印字符数组的前 N ​​个字符,其中 N 不是常量,可以使用 * 指定长度作为单独的参数给出。例如,给定一个不包含空字符的已知长度的字符数组,您可以这样做:

const char s[5] = "hello"; /* no terminating null character */
printf("%.*s\n", (int)sizeof s, s);

请注意,sizeof 在这里起作用只是因为s 是一个数组;如果它是一个指针,sizeof 会给你一个指针的大小,而不是数组的大小。另请注意,* 需要一个 int 类型的参数;因为 printf 是一个可变参数函数,而 sizeof 产生一个 size_t 类型的值,所以在这种情况下您需要强制转换。

关于c - 固定字符串的 printf 格式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30958232/

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