1 函数原型
strcpy():将str指向的字符串拷贝至dest指向的内存空间中,函数原型如下:
char *strcpy(char *dest, const char *src);
2 参数
strcpy()函数有两个参数src和dest:
- 参数src是指向待拷贝字符串的指针,类型为char*型;
- 参数dest是指向拷贝目的地的指针,类型为char*型。
3 返回值
strcpy()函数的返回值类型为char*型,返回值为dest。
4 使用说明
- strcpy()函数在拷贝字符串时连同字符串末尾的空字符’\0’一起拷贝;
- strcpy()函数在拷贝字符串时不检查dest指向的内存空间的大小,必须保证dest指向的内存空间足够大,能够容纳src指向的字符串,否则会导致溢出错误。
C语言标准描述如下:
1. Copies the null-terminated byte string pointed to by src, including the null terminator, to the character array whose first element is pointed to by dest.
2. The behavior is undefined if the dest array is not large enough.
3. The behavior is undefined if the strings overlap.
4. The behavior is undefined if either dest is not a pointer to a character array or src is not a pointer to a null-terminated byte string.
5 示例
5.1 示例1
dest指向的内存空间为空,代码如下所示:
int main()
{
//
char src[] = "source string";
char dest[20] = { 0 };
//
printf("src : %s\n", src);
//
strcpy(dest, src);
printf("dest : %s\n", dest);
return 0;
}
代码运行结果如下图所示:
代码及运行结果分析如下:
- 字符串拷贝前dest字符数组储存的元素如下图所示:
- 字符串拷贝后des字符数组储存的元素如下图所示:
3. 通过对比拷贝前后dest指向的内存空间的内容,可以确定:strcpy()函数在拷贝字符串时连同字符串末尾的空字符’\0’一起拷贝。