我测试浅拷贝的结构与此代码:为什么结构浅拷贝不起作用?
#include "stdio.h"
#include "conio.h"
int main() {
struct str {
char * name;
int value;
};
struct str str_1 = {"go", 255};
struct str str_2;
str_2 = str_1;
str_1.name = "back";
printf("%s\n",str_1.name);
printf("%s\n",str_2.name);
printf("\n");
system("pause");
return 0;
}
我期待的结果应该是:
back
back
但它是:
back
go
编辑:我预计,因为浅拷贝,str_1.name
和str_2.name
应该始终指向相同的pla CE。
编辑:并与动态分配的,我得到了我的预期:
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main() {
struct str {
char * name;
int value;
};
struct str str_1;
struct str str_2;
str_1.name = (char*) malloc(5);
strcpy(str_1.name,"go");
str_2 = str_1;
strcpy(str_1.name,"back");
printf("%s\n",str_1.name);
printf("%s\n",str_2.name);
printf("\n");
system("pause");
return 0;
}
结果是:
back
back
什么是我误会吗?
我不知道。你为什么期望你的预期?这不是什么“浅”的意思... –
恕我直言,这个问题没有错。 “显而易见度”的程度不应该吸引downvotes。广义相对论对一些民间人士来说显而易见 – Bathsheba
@Bathsheba:没错,但描述期望的缺乏吸引了低估。很难解释为什么这个世界不符合隐藏的期望。 –