总结:strcpy是深拷贝,=都是浅拷贝;但是之间的修改不会影响另外一个;
1、使用strcpy时会有两个“字符串”;而使用“=”只有一个字符串;
2、strcpy是将字符串拷贝到指定的地址;
像了解其中奥秘必须要读懂下面几行代码;
void test() {
1 char * str1 = "字符串";//在栈区声明一个 char* 变量str1 并初始化它,让他指向data区的 “字符串”
2 //char * str1 ="字符串2";//erro 多次初始化
3 char * str2 = str1;//在栈区声明一个char* 变量str2;并给将str1中的值复制给它.
//str1中存储的就是堆区“字符串”的地址;这一个过程不是初始化,
//所以后面str2还可执行str2 = "字符串3"这一操作
4 str2 = "字符串3";
}
查一查手册
strcpy的内存模型
从“把 src 所指向的字符串复制到 dest”这一句我们能知道大概是下面这个
代码验证;
void test() {
char * str1 = "1234";
char * str2 = (char *)malloc(4);
printf("str1的地址:%p\n", str1);
printf("str2的地址:%p\n", str2);
strcpy(str2, str1);
printf("str2使用了strcopy后的地址:%p\n", str2);
str2 = "2345";
printf("改变str2后str1的值:%s\n", str1);
printf("改变str2后str1的地址;%p\n", str1);
printf("改变str2的str2的地址:%p\n", str2);
}
打印结果:
“=” 的模型
代码验证
void test1() {
char * str1 = "1234";
char * str2 = (char *)malloc(4);
printf("str1的地址:%p\n", str1);
printf("str2的地址:%p\n", str2);
str2 = str1;
printf("执行了str2 = str1之后str2的地址:%p\n", str2);
str2 = "2345";
printf("改变str2后str1的值:%s\n", str1);
printf("改变str2后str1的地址;%p\n", str1);
printf("改变str2的str2的地址:%p\n", str2);
}
打印结果