1 函数原型
strcpy():拷贝字符串,函数原型如下:
char * strcpy ( char * destination, const char * source );
cstring库描述如下:
Copy string
1. Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point).
2. To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.
- strcpy()函数:
(1)将source指向的字符串复制到destination指向的数组中,包括末尾的空字符’\0’; - 注意事项
(1)目标空间足够大:必须确保目标数组destination有足够的空间来存放源字符串source(包括末尾的空字符’\0’);
(2)内存不能够重叠:source和destination所指向的内存区域不能重叠。
2 参数
strcpy()函数有两个参数source和destination:
- 参数source是指向源字符串的指针,类型为char*型;
- 参数destination是指向目标数组的指针,类型为char*型。
cstring库描述如下:
destination
1. Pointer to the destination array where the content is to be copied.
source
1. C string to be copied.
3 返回值
strcpy()函数的返回值类型为char*型:
- 返回指向目标字符串destination的指针。
cstring库描述如下:
1. destination is returned.
4 示例
4.1 示例1
示例代码如下所示:
int main()
{
//
char src[] = "Hello world.";
char dest[100] = { 0 };
//
strcpy(dest, src);
//
printf("The length of source string \"%s\" is %zu.\n", src, strlen(src));
//
printf("The length of destination string \"%s\" is %zu.\n", dest, strlen(dest));
//
return 0;
}
代码运行结果如下图所示:
4.2 示例2
编写自己的字符串拷贝函数,示例代码如下所示:
char* my_strcpy(char* dest, const char* src) {
//
assert(dest != NULL);
assert(src != NULL);
//
char* orig_dest = dest;
//
while ((*dest++ = *src++));
//
return orig_dest;
}
int main()
{
//
char src[] = "Hello world.";
char dest[100] = { 0 };
//
strcpy(dest, src);
//
printf("The length of source string \"%s\" is %zu.\n", src, strlen(src));
//
printf("The length of destination string \"%s\" is %zu.\n", dest, strlen(dest));
//
return 0;
}
代码运行结果如下图所示: