1:模拟实现strcpy函数以及strncpy函数
strcpy函数:顾名思义字符串复制函数:原型:extern char *strcpy(char *dest,char *src); 功能:把从src地址开始且含有NULL结束符的字符串赋值到以dest开始的地址空间。
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main()
{
char* msg = "hello";
char buf[32];
void mystrcpy();
mystrcpy(buf,msg);
printf("%s",buf);
system("pause");
return 0;
}//测试代码
//返回值为空
void mystrcpy(char* buf,const char* msg)
{
assert(buf);
assert(msg);
while(*buf = *msg)
{ buf++ ; msg++;}
}
<pre name="code" class="cpp" style="font-size: 17.9104px;">//返回值不为空
<pre name="code" class="cpp">char *mystrcpy(char* buf,const char* msg)
{
char *ret = buf;//用于接收返回值
assert(buf != NULL && msg != NULL);
while ((*buf++ = *msg++)!='\0');
return ret;
}
strncpy函数:多个n代表可以指定字符个数进行赋值。原型:char * strncpy(char *dest, char *src, size_tn); 功能:将字符串src中最多n个字符复制到字符数组dest中,返回指向dest的指针。
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
char *mystrncpy(char* buf,const char* msg,int count)
{
int i= 0;
char *ret = buf;
assert (buf != NULL && msg != NULL);
while ((i++<count) && (*buf++ = *msg++));
{;}
if (*(buf)!= '\0')
*buf = '\0';
return ret;
}
int main()
{
char *b = "abcdef";
char a[32];
mystrncpy(a, b, 5);
printf("%s\n",a);
system("pause");
return 0;
}