最近使用strcpy这个函数比较多,关于如何使用,以及使用时碰到的一些问题,在此做一个总结。文笔有限,请见谅。
下列是strcpy( ) 函数的声明
char *strcpy(char *dst, const char *src);
参数
dest – 指向用于存储复制内容的目标数组。
src – 要复制的字符串。
返回值
该函数返回一个指向最终的目标字符串 dest 的指针。
该函数功能简要讲就是将src指向的字符串复制到dst,注意是字符串,关于strcpy和strcnpy的区别最后讲。
注意事项
strcpy复制字符串,直到src指针指向为‘\0’时将会停止字符串的复制;
strcpy的本身属性:即strcpy只用于字符串复制,并且它不仅复制字符串内容之外,还会复制字符串的结束符;
代码试验
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char* str1 = NULL;
char* str2 = NULL;
str1 = (char*)malloc(12*sizeof(char));
if(str1 == NULL) {
exit(1);
}
str2 = (char*)malloc(10*sizeof(char));
if (str2 == NULL) {
exit(1);
}
strcpy(str1,"hello world");
strcpy(str2,"hello world!!!!!");
printf("%s\n",str1);
printf("%s\n",str2);
return 0;
}
hello world
hello world!!!
/usercode/file.cpp: In function ‘int main()’:
/usercode/file.cpp:56:11: warning: ‘void* __builtin_memcpy(void*, const void*, long unsigned int)’ writing 17 bytes into a region of size 10 overflows the destination [-Wstringop-overflow=]
56 | strcpy(str2,“hello world!!!”);
出现数组越界的问题,strcpy复制的时候第一个数组空间不够
补充
一、strcpy和memcpy主要有以下3方面的区别。
1、复制的内容不同。strcpy只能复制字符串,而memcpy可以复制任意内容,例如字符数组、整型、结构体、类等。
2、复制的方法不同。strcpy不需要指定长度,它遇到被复制字符的串结束符"\0"才结束,所以容易溢出。memcpy则是根据其第3个参数决定复制的长度。
3、用途不同。通常在复制字符串时用strcpy,而需要复制其他类型数据时则一般用memcpy
二、strcpy和strncpy区别
strcpy() 函数用来复制字符串,strncpy()用来复制字符串的前n个字符;