目录
strcpy函数的两个参数(char* destination 和 char* source)
strcpy函数的功能介绍
- 用于字符串拷贝,将源头字符串的内容拷贝到目的地字符串中,包括源头字符串中的'\0'也一同拷贝到目的地字符串中
- strcpy函数的头文件 - #include<string.h>
strcpy函数的两个参数(char* destination 和 char* source)
- char* destination - char*类型的destination指针变量,destination英译中为目的地的意思,由此可以理解为将目的地字符串的起始地址传递到char* destination接收
- char* source - char* 类型的source指针变量,source英译中为源头的意思,由此可以理解为将源头字符串的起始地址传递到char* source接收
strcpy函数的返回值(char*)
strcpy函数的返回值为char*类型的指针变量,也就是返回目的地字符串的起始地址
strcpy函数的实现
不接收strcpy函数的返回值的实现
#include<stdio.h>
#include<string.h>
int main()
{
//源头字符串
char source[] = "hello world";
//目的地字符串
char dest[20] = { 0 };
//拷贝
strcpy(dest, source);
//验证
printf("%s\n", dest);
return 0;
}
接收strcpy函数的返回值的实现
#include<stdio.h>
#include<string.h>
int main()
{
//源头字符串
char source[] = "hello world";
//目的地字符串
char dest[20] = { 0 };
//拷贝
char* ret = strcpy(dest, source);
//验证
printf("%s\n", ret);
return 0;
}
strcpy函数的注意事项
- 目的地字符串的内存大小必须大于或者等于源头字符串的内存大小
- 目的地字符串和源头字符串的地址都不能为空(NULL)
验证:源头字符串的'\0'是否拷贝到了目的地字符串
- 将目的地字符串初始化为相同的字符
- strcpy函数运行完之后,查看目的地字符串的内容,看是否将'\0'拷贝过来
#include<stdio.h>
#include<string.h>
int main()
{
//源头字符串
char source[] = "hello world";
//目的地字符串
char dest[20] = "xxxxxxxxxxxxxxxx";
//拷贝
char* ret = strcpy(dest, source);
//验证
printf("%s\n", ret);
return 0;
}
拷贝前
拷贝后