【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’为止,如下图所示。
    在这里插入图片描述
  • 1
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值