我多次使用strncat
,但现在检查它在标准中的正式定义:
#include <string.h>
char *strncat(char * restrict s1,
const char * restrict s2,
size_t n);
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.
通常我会认为s1
和s2
只是指向char 的指针。但正如所见,标准对它们的称呼不同:
s1
指向的字符串s2
指向的数组
s1
和 s2
之间的唯一区别是 const 限定符 - 这就是为什么一个被称为 array 而另一个被称为 < strong>字符串?
此外,在脚注中:
Thus, the maximum number of characters that can end up in the array pointed to by s1 is strlen(s1)+n+1.
所以这里他们以不同的方式引用 s1
:s1
指向的数组(不是字符串)
调用 s1
和 s2
的这些不同方式有什么含义吗?
最佳答案
The only difference between s1 and s2 is a const qualifier
不,不一定。
目标数组
s1
必须已经以 null 结尾。所以,它可以安全地称为 string。引用
C11
,章节 §7.1.1/p1,术语定义A string is a contiguous sequence of characters terminated by and including the first null character. [...]
但是,对于源数组
s2
,空终止符不是必须的,以防给定大小n
小于数组的实际长度。因此,它必须始终不是字符串。
所以,TL;DR - destination 数组将始终是一个string(因此可以互换使用)但是没有这样的保证对于源数组。
此外,为了强调用法中的差异,让我们将其与strcat()
的描述进行比较,后者具有相似的语法,但大小有所不同。因此,两个参数都需要以 null 结尾,因为函数没有其他方法可以确定 source 数组 s2
的结尾。因此,请注意第 7.24.3.1 章中的措辞(强调我的)
The
strcat
function appends a copy of the string pointed to bys2
(including the terminating null character) to the end of the string pointed to bys1
. The initial character ofs2
overwrites the null character at the end ofs1
. If copying takes place between objects that overlap, the behavior is undefined.
这里,两个数组必须是字符串,因此也是用法。
关于c - 指向 char 的指针,不同的术语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37921242/