strcpy 函数是字符串拷贝函数,他将 src所指字符串拷贝到 dest所指字符串中,包括’\0’
//模拟实现strcpy函数
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
char *my_strcpy(char *dest, const char *src)
{
assert(dest);
assert(src);
char *tmp = dest;
while (*dest++ = *src++)//'\0'也赋给了dest
{
;
}
return tmp;
}
int main()
{
char a[20];//数组大小要能容纳所给的字符
char b[] = "abcdef";
my_strcpy(a, b);
printf("%s\n",a);
system("pause");
return 0;
}
strncpy函数是将src所指字符串的前n个字符拷贝到dest所指字符串中,若需要拷贝的字符个数大于 src所指向字符串的字符个数,将*src中的字符拷贝过去之后,其余部分补上’\0’
//模拟实现strncpy函数
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
char *my_strncpy(char *dest, const char *src, int count)
{
assert(dest);
assert(src);
while ((count--)&&(*dest++ = *src++))
{
;
}
if (count > 0)
while (--count)
{
*dest++ = '\0';
}
}
int main()
{
char a[] = "abcdef";
char b[] = "ghi";
my_strncpy(a, b, 5);
printf("%s\n",a);
system("pause");
return 0;
}