C语言:模拟实现strcpy
来源:互联网 发布:股票智能交易软件 编辑:程序博客网 时间:2024/06/13 01:34
模拟实现strcpy:
(1)字符串拷贝函数就是将原串拷贝到新串,而原串无需变换,可以用const来修饰。包括‘\0’全部拷贝到新的子串dest。
(2)while ((*dest++ = *src++) )
{
;
}
这种遍历程序连同‘\0’一起拷贝了while ((*dest++ = *src++) )相当于while ((*dest++ = *src++) !=‘\0’),上一次拷贝到最后一个字符时后置加加,将src变为‘\0’了,而下次再进入while循环时先执行*dest++ = *src++,dest也拷贝为‘\0’.而此时不满足该条件跳出while循环。但是此时已经拷贝了'\0'了。这也是程序的先后性。
或者可以:while (*src)
{
*dest = *src;
dest++;
src++;
}
原串为‘\0’时跳出,并未拷贝‘\0’,要赋值*dest = '\0',需要赋值 *dest = '\0'。
其实对于以上两种方法均可都执行*dest = '\0'操作,即使赋值过再赋值也无妨。
(3)另外要说的一点是:自加有副作用,因此return dest 可能读到最后'\0'就不输出了。因此需要定义新变量来保存首地址
char *ret = dest以便返回。
代码如下:
#include<stdio.h>#include<stdlib.h>#include<assert.h>char* my_strcpy(char* dest, const char* src) //const使在函数中不能修改*src原先的值 { assert(dest); //两次断言-->检验参数,增加代码健壮性 assert(src); char* strdest = dest; //保存原始指针地址 while (*src) { *dest++ = *src++; } *dest = '\0'; return strdest;}int main(){ char arr1[] = "hello world!"; char arr2[20] ; char* ret = my_strcpy(arr2, arr1); printf("%s", ret); system("pause"); return 0;}
本文出自 “Han Jing's Blog” 博客,请务必保留此出处http://10740184.blog.51cto.com/10730184/1714516
- C语言:模拟实现strcpy
- 模拟实现strcpy(C语言)
- C语言-模拟实现strcpy
- c语言模拟实现strcpy
- 【c语言】模拟实现库函数strcpy函数
- C语言,模拟实现strcpy、strlen函数
- c语言模拟实现strcpy函数
- C语言 模拟实现strcpy 与 strlen
- 【C语言】模拟实现strcpy()、strncpy()函数
- 【c语言】模拟实现strcpy函数:
- c 语言之 模拟实现 strcpy 和 strcat 函数
- 用c语言.模拟实现strcpy,strcat,strcat,memcpy,memmove
- C语言中模拟实现strcpy,strstr,strcat函数
- 【C语言】模拟实现strcpy、strcat、strcmp函数
- C语言模拟实现strcpy、strlen、strcmp、strcat
- C语言:模拟实现strlen、strcpy、strcmp、strReverse、strcat函数
- 【C语言】、模拟实现strlen,strcmp,strcpy,strcat,strstr函数
- C语言模拟实现strcpy、strncpy、strcmp、strcat、strstr
- 【笔试题】C语言:模拟实现strcmp
- C语言函数变参问题
- 【笔试题】C语言:模拟实现strcat
- 安装 Maven
- Android Service完全解析,关于服务你所需知道的一切(上)
- C语言:模拟实现strcpy
- 【笔试题】C语言:模拟实现strncmp
- 【笔试题】C语言:模拟实现strncat
- 线程简介
- 【面试题】C语言:模拟实现strncpy,尝试比较strncpy与strcpy区别。
- 【面试题】C语言:模拟实现内存放置函数memset()
- Context详解
- 【面试题】C语言:模拟实现memcmp,试比较memcmp与strcmp,strncmp的区别
- 常用正则表达式大全