1.strcpy介绍
strcpy --- 字符串拷贝
char* strcpy( char* destination, const char* source);
源字符串必须以‘\0’结束;
会将源字符串的‘\0’拷贝到目标空间,目标空间必须足够大并且可变
2.如何使用
char*arr1 = "abcedf"; // 常量字符串不可以被更改;
char arr1[] = "abcdef"; //这种写法是正确的
char*arr1 = "abc";
char*arr2 = "abcde";
strcpy(arr1,arr2); // arr1的空间不足以让arr2拷贝过去
strcpy(arr2,arr1); // 这种写法是正确的
3.strcpy的实现
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<string.h>
char* my_strcpy(char* destination, const char* source)
{
assert(destination != NULL);
assert(source != NULL);
char* ret = destination;
//拷贝source指向的字符串到destination指向的空间,包含'\0'
while (*destination++ = *source++)
{
;
}
//返回目的空间的起始地址
return ret;
}
int main()
{
char arr1[] = { "abcdefghi" };
char arr2[] = { "zsl" };
my_strcpy(arr1, arr2);
printf("%s\n", arr1);
return 0;
}