该函数用于拷贝count个字符。
函数原型及实现:
char *strncpy(char *dst, const char *src, size_t count)
{
assert((dst != NULL) && (src != NULL));
char *tmp = dst;
while (count-- && (*dst++ = *src++) != '/0')
{
/* nothing */;
}
return tmp;
}
注意:
1. count一定要小于dst的大小。
2.调用完该函数后一定要加上一句:dst[count] = '/0';否则不安全,如strlen等函数要求参数必须是以'/0'结尾的字符串。
因为当count小于src的大小时,src的结束字符'/0'并不会被拷贝,故应该为dst加上一个结束符。
例:
char *str = "123456";
char dst[7];
int count = 6;
strncpy(dst, str, count); //count=6一定要小于dst的长度(7)。
dst[count] = '/0';