6

浅谈strcpy()实现

 3 years ago
source link: https://blog.csdn.net/weixin_43580319/article/details/112140811
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

浅谈strcpy()实现

original.png
天津 唐秙 2021-01-04 11:11:05 articleReadEyes.png 1053
分类专栏: C语言

strcpy 覆盖拷贝

  1. 被拷贝的字符串必须以’\0’结束。

  2. 目标空间要足够大,至少要能放的下拷贝的东西。

  3. 目标空间的值是可以修改,比如常量区的字符串,不能够修改,就不能使用。

  4. 会将被拷贝的字符串中的’\0’拷贝到目标空间。

  5. 函数实现。
    方法一

     char* my_strcpy(char* dst, const char* src)
     {
     	const ret = dst;
     	while (*src)
     	{
     		*dst = *src;
     		dst++;
     		src++;
     	}
     	*dst = '\0';
     	return ret;
     }
    

       ret记录字符串的首地址,将函数的返回值设置成为一个char*,是为了在调用函数的时候可以像my_strcpy(str1, my_strcpy(str1, p1));这样嵌套,由于strcpy拷贝是拷贝’\0’的,因此在最后,我们需要吧*dst最后所指向的内容改为’\0’。
    方法二

     char* my_strcpy(char* dst, const char* src)
     {
     	const ret = dst;
     	//先赋值,再判断,只要不是\0,代码就继续
     	while (*dst++ = *src++);
     	return ret;
     }		
    

      方法二就相对方法一进行了简化,采用前置++的方式,前置++的优先级高于*,因此没循环一次,指针向后移一下,再将src的值赋给dst。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK