【C语法学习】25 - strncpy()函数

1 函数原型

strncpy():将str指向的字符串的前n个字符拷贝至dest指向的内存空间中,函数原型如下:

char *strncpy(char *dest, const char *src, size_t n);

2 参数

strncpy()函数有三个参数src、dest和n:

  1. 参数src是指向待拷贝字符串的指针,类型为char*型;
  2. 参数dest是指向拷贝目的地的指针,类型为char*型;
  3. 参数n是拷贝的字符数量,类型为size_t(unsigned int)型。

3 返回值

strncpy()函数的返回值类型为char*型,返回值为dest。

4 使用说明

  1. 如果src指向的字符串长度小于n,strncpy()函数在拷贝字符串时连同字符串末尾的空字符’\0’一起拷贝,并在拷贝后的字符串末尾填充空字符’\0’,凑齐n个字符;
  2. 如果src指向的字符串长度大于n,strncpy()函数在拷贝字符串时仅拷贝字符串的前n个字符,且不在拷贝后的字符串末尾添加空字符’\0’。

C语言标准描述如下:

1. Copies at most count characters of the character array pointed to by src (including the terminating null character, but not any of the characters that follow the null character) to character array pointed to by dest.
2. If count is reached before the entire array src was copied, the resulting character array is not null-terminated.
3. If, after copying the terminating null character from src, count is not reached, additional null characters are written to dest until the total of count characters have been written.
4. The behavior is undefined if the character arrays overlap, if either dest or src is not a pointer to a character array (including if dest or src is a null pointer), if the size of the array pointed to by dest is less than count, or if the size of the array pointed to by src is less than count and it does not contain a null character.

5 示例

5.1 示例1

待拷贝字符串长度小于n,代码如下所示:

int main()
{
   //
   char src[] = "hello world";
   char dest[20];
   //
   strncpy(dest, src, 15);
   puts(dest);

   return 0;
}

拷贝前dest字符数组储存的元素如下图所示:

在这里插入图片描述

拷贝后dest字符数组储存的元素如下图所示:

在这里插入图片描述
代码运行结果如下图所示:

在这里插入图片描述

代码及运行结果分析如下:

  1. src指向的字符串"hello world"长度小于n=15,strncpy()函数在拷贝至dest的字符串末尾填充空字符’\0’,补齐15个字符。

5.2 示例2

待拷贝字符串长度大于n,代码如下所示:

int main()
{
   //
   char src[] = "hello world";
   char dest[20];
   //
   strncpy(dest, src, 5);
   puts(dest);

   return 0;
}

拷贝前dest字符数组储存的元素如下图所示:

在这里插入图片描述

拷贝后dest字符数组储存的元素如下图所示:

在这里插入图片描述

运行结果如下图所示:

在这里插入图片描述

代码及运行结果分析:

  1. src指向的字符串"hello world"长度大于n=5,strncpy()函数在拷贝至dest的字符串末尾不会添加空字符’\0’,在打印时发生了越界访问,直至遇到空字符’\0’为止,如下图所示。
    在这里插入图片描述