C语言–模拟实现strncpy函数
一、strncpy说明
strncpy格式如下
char* strncpy(char* destination, const char* source, size_t num)
即:复制 num个source指针指向的字符到destination。当遇到字符终止符’\0’且复制的个数还没有达到num个时,在destination后面补’\0’。 举例说明:
int main()
{
char a[20] = "abcdef";
char b[] = "xyz";
strncpy(a, b, 2);
printf("%s\n", a);
return 0;
}
'//输出结果为xycdef '
二、模拟实现strncpy函数
char* my_strncpy(char* destination, const char* source, size_t n)
{
char* cp = destination;
int i = 0;
while (*source && i < n)
{
*cp++ = *source++;
i++;
}
for (int j = i; j < n; j++)
{
*cp++ = 0;
}
return destination;
}
int main()
{
char a[20] = "abcdefghi";
char b[] = "xyz";
my_strncpy(a, b, 6);
printf("%s\n", a);
return 0;
}
|