strncpy函数,strncat函数

本文深入解析strncpy和strncat两个C语言字符串处理函数。strncpy用于安全地复制固定数量的字符,避免缓冲区溢出;strncat则用于连接字符串,同样限定字符数以增强安全性。文章通过实例说明如何使用这两个函数,并强调了在编程实践中考虑边界条件的重要性。

strncpy

char * strncpy ( char * destination, const char * source, size_t num );
  • Copies the first num characters of source to destination. If the end of the source C string (which is
    signaled by a null-character) is found before num characters have been copied, destination is padded
    with zeros until a total of num characters have been written to it.
  • 拷贝num个字符从源字符串到目标空间。
  • 如果源字符串的长度小于num,则拷贝完源字符串之后,在目标的后边追加0,直到num个。
	char str1[10] = "hehe";
	char str2[100] = "sing dance rap baskertball";
	strncpy(str1, str2, 9);
	//9,做人留一线

在这里插入图片描述
在一定程度上避免访问越界

strncat函数

char * strncat ( char * destination, const char * source, size_t num );
  • Appends the first num characters of source to destination, plus a terminating null-character.
  • If the length of the C string in source is less than num, only the content up to the terminating null character is copied.
    从源字符串中num个字符拼接到目标字符串,当源字符串小于num,在目标后面追加0,直到num
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值