strncpy函数模拟实现
strncpy函数在cplusplus网站中的定义
模拟实现源码
//模拟实现
#include <stdio.h>
#include <string.h>
#include <assert.h>
char* my_strncpy(char* destination, const char* source, size_t num)
{
assert(destination && source);//对指针进行断言,确保不是NULL指针
char* ret = destination;//保存目的地址
while (num--)
{
*destination = *source;
destination++;
source++;
}
return ret;
}
int main()
{
char arr1[] = "abcdef";
char arr2[20] = "xxxxxxxxxxxxxxx";
char arr3[20] = { 0 };
char* ret1 = my_strncpy(arr2, arr1, 4);
char* ret2 = my_strncpy(arr3, arr1, 4);
printf("arr1:%s\n", arr1);
printf("arr2:%s\n", arr2);
printf("ret1:%s\n", ret1);
printf("arr3:%s\n", arr3);
printf("ret2:%s\n", ret2);
return 0;
}
执行结果