#define _CRT_SECURE_NO_WARNINGS 1
实现字符串复制函数——strcpy;
#include<stdio.h>
#include<string.h>
int main()
{
char arr1[] = "hello world";
char arr2[20] = { 0 };
strcpy(arr2, arr1);
printf("%s\n", arr2);
return 0;
}
#include<stdio.h>
void my_strcpy(char* dest, char* src)
{
while (*src != '\0')
{
*dest = *src;
src++;
dest++;
}
*dest = *src; //将'\0'赋值给*dest;
}
int main()
{
char arr1[] = "hello world";
char arr2[20] = { 0 };
my_strcpy(arr2, arr1);
printf("%s\n", arr2);
return 0;
}
//代码优化
#include<stdio.h>
void my_strcpy(char* dest, char* src)
{
while (*src != '\0')
{
*dest++ = *src++; //优化成为后置++;
}
*dest = *src; //将'\0'赋值给*dest;
}
int main()
{
char arr1[] = "hello world";
char arr2[20] = { 0 };
my_strcpy(arr2, arr1);
printf("%s\n", arr2);
return 0;
}
//代码再次优化
#include<stdio.h>
void my_strcpy(char* dest, char* src)
{
while (*dest++ = *src++) //当对src解引用时候,如果他是'\0'。\0的阿斯克码值是0。条件为假就会退出while循环。
{
;
}
}
int main()
{
char arr1[] = "hello world";
char arr2[20] = { 0 };
my_strcpy(arr2, arr1);
printf("%s\n", arr2);
return 0;
}
//代码再次优化
#include<stdio.h>
#include<assert.h>
void my_strcpy(char* dest, char* src) //因为dest和src都是指针,我们害怕他们是空指针,所以我们可以使用assert;
{
/*assert(dest != NULL);
assert(src != NULL);*/
//也可以这样写
assert(dest && src); // 因为NULL为 0 ;
while (*dest++ = *src++)
{
;
}
}
int main()
{
char arr1[] = "hello world";
char arr2[20] = { 0 };
my_strcpy(arr2, NULL);
printf("%s\n", arr2);
return 0;
}
09-08
984
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-17
699
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)