c - 指向 char 的指针,不同的术语

标签 c arrays string language-lawyer

我多次使用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.

通常我会认为s1s2 只是指向char 的指针。但正如所见,标准对它们的称呼不同:

  • s1指向的字符串
  • s2指向的数组

s1s2 之间的唯一区别是 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 指向的数组(不是字符串)

调用 s1s2 的这些不同方式有什么含义吗?

最佳答案

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 by s2 (including the terminating null character) to the end of the string pointed to by s1. The initial character of s2 overwrites the null character at the end of s1. If copying takes place between objects that overlap, the behavior is undefined.

这里,两个数组必须是字符串,因此也是用法。

关于c - 指向 char 的指针,不同的术语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37921242/

相关文章:

c - 为什么将函数插入示例代码后会出现错误?

Python 字符串比较似乎不起作用

java - 如何将对象数组合并为单个格式化字符串

c - 从应用程序 makefile 运行库 makefile

关于 C 中位域排序语义的说明

php - 如何使 ZEND_BEGIN_ARG_INFO_EX 控制传递给 PHP 扩展的参数数量?

html - 在 Angular 2/4 中使用 typescript 动态创建 HTML 元素数组

php - 将 foreach 应用于多个数组?

javascript - JavaScript 中的数字排序代码错误

python - 从字符串列表实例化两个 2D numpy 数组