定义
函数原型:
char *strncpy(char *dst, const char *src, size_t n);
函数说明:
函数strncpy从src指向的数组中最多复制n个字符(若数组中存在多个空字符,则不复制第一个空字符后面的所有字符字符,但复制第一个空字符)到dst指向的数组中。
如果src指向的数组是一个比n短的字符串,则在dst定义的数组后面补空字符,直到写入了n个字符。
返回值:
函数strncpy返回dst的值。
实例
1、 strncpy的作用与strcpy的作用类似,主要用于字符数组的赋值:
int main(void)
{
char src[5] = "abcd";
char dst[5] = "qwer";
strncpy(dst,src,3);
printf("dst:%sn",dst);
return 0;
}
打印结果为abcr
在c语言中,字符数组赋值不能直接写dst = src,所以使用strncpy将字符数组src中的前3个字符复制到dst字符数组中,但由于strcpy不在复制结束时添加‘ ’所以输出abcr。
2、 当n大于dst数组总大小时:
int main(void)
{
char src[] = "abcdefg";
char dst[5] = "";
strncpy(dst,src,5);
printf("dst:%sn",dst);
return 0;
}
打印结果为abcdefg。
同strcpy一样出现越界问题。使用时要注意。
3、 当n大于src数组元素总个数时:
#include
#include
int main(void)
{
char src[3] = "ab";
char dst[6] = "qwert";
strncpy(dst,src,4);
printf("dst:%sn",dst);
int i = 0;
for(;i < 5;i++)
{
printf("%d ",dst[i]);
}
puts("");
return 0;
}
输出ab
97 98 0 0 116。
通过结果可以看出,如果src指向的数组是一个比n短的字符串,则在将src中的字符复制到dst数组之后,再补空字符,直到写入了n个字符。
4、 在src字符数组中若存在多个‘ ’时,可采用memcpy进行复制,使用strncpy和strcpy时,都只复制到第一个’ ’为止,其余补’ ’。
5、 由于strncpy存在给目标字符串dst补空字符的行为,所以其运行效率也受到一定影响。