其他分享
首页 > 其他分享> > C语言--模拟实现strncpy函数

C语言--模拟实现strncpy函数

作者:互联网

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;
}

在这里插入图片描述

标签:--,destination,++,C语言,char,source,int,strncpy
来源: https://blog.csdn.net/qq_46480020/article/details/121802910