gpt4 book ai didi

c - strncat() 总是空终止吗?

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

考虑这段代码:

limit = sizeof(str1)-strlen(str1)-1;
strncat(str1,str2,limit);

如果 str2 长度大于 limitstrncat Nul 是否终止 str1 或者我必须添加这个代码,例如 strncpy?

str1[sizeof(str1)-1] = '\0'

最佳答案

它总是空终止。

引用 C11,章节 §7.24.3.2,(强调我的)

The strncat function appends not more than n characters (a null character and characters that follow it are not appended) from the array pointed to by s2 to the end of the string pointed to by s1. The initial character of s2 overwrites the null character at the end of s1. A terminating null character is always appended to the result.

还有脚注

Thus, the maximum number of characters that can end up in the array pointed to by s1 is strlen(s1)+n+1.

关于c - strncat() 总是空终止吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41652122/

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