Q:为什么需要使用strcpy?
A:1.前人已经设计好函数,我们不需要重复制造轮子。
2.如果有两个字符串指针(pts,pts1),来进行字符串拷贝
//部分代码片段
char * pts ="hello";
char * pts1 ="welcome";
pts = pts1;
这种方式并不是字符串拷贝,而是拷贝的字符串地址,是将pts
指向pts1
的位置,而原来pts
指向的位置内容并未发生改变
。
一.相同点
- 功能相同,都是用来进行字符串拷贝。
第二参数(源字符串)
字符串拷贝到第一个参数(目标字符串)
字符串中。
二.不同点
strcpy
拷贝字符串不会检测目标字符串
是否能容纳下源字符串长度
。strncpy
拷贝字符串会指定拷贝字符的最大数量
,比strcpy
更安全一些。strncpy
拷贝字符串指定长度很有可能源字符长度大于拷贝字符的数量,这个时候会出现目标字符串没有结束标志的情况,需要再目标字符串最后的字符增加结束表示符('\0')
。
注:需要注意的是拷贝函数会将末尾的结束标志符('\0')一并拷贝进目标字符串中。
三.示例
- strcpy
#include <stdio.h>
#include <string.h> //使用strcpy、strncpy必须导入头文件
#define SIZE 40
#define LMT 5
#define WORD "Grand"
int main(void){
char name[SIZE]="hello,Vic.";
char test[LMT]="Wgwes";
strcpy(name+6,WORD);
//strcpy(test+1,WORD); //增加test拷贝报错
puts(name);
puts(test);
return 0;
}
输出结果:
hello,Grand
增加test拷贝结果:
test.c:11:2: warning: ‘strcpy’ will always overflow;destination buffer has size 4, but the source string has length 6
(including NUL byte) [-Wfortify-source]
strcpy(test+1,WORD);
- strncpy
#include <stdio.h>
#include <string.h>
#define SIZE 10
#define WORDS "VIC"
int main(void){
char name[SIZE]="He is Gris";
//从数组第6个位置开始拷贝,拷贝最大字符数3
strncpy(name+6,WORDS,3);
//防止拷贝源数组大于目标数组长度丢失字符串结束标志
name[SIZE-1]='\0';
puts(name);
return 0;
}
输出结果:
He is VIC