【发布时间】:2012-02-04 14:30:42
【问题描述】:
我在两个代码中都在做同样的事情。
在代码 1 中:我使用了 char * 并在 main 中使用 malloc 分配空间。
在代码 2 中:我出于相同目的使用了 char 数组。但是为什么输出不一样呢?
代码 1:
struct node2
{
int data;
char p[10];
}a,b;
main()
{
a.data = 1;
strcpy(a.p,"stack");
b = a;
printf("%d %s\n",b.data,b.p); // output 1 stack
strcpy(b.p,"overflow");
printf("%d %s\n",b.data,b.p); // output 1 overflow
printf("%d %s\n",a.data,a.p); // output 1 stack
}
代码 2:
struct node1
{
int data;
char *p;
}a,b;
main()
{
a.data = 1;
a.p = malloc(100);
strcpy(a.p,"stack");
b = a;
printf("%d %s\n",b.data,b.p); //output 1 stack
strcpy(b.p,"overflow");
printf("%d %s\n",b.data,b.p); // output 1 overflow
printf("%d %s\n",a.data,a.p); // output 1 overflow(why not same as previous one?)
}
【问题讨论】:
-
@birryree
b.p是从a.p浅拷贝的。 -
@Chad - 是的,我错过了
b = a行,所以我删除了我的评论。 -
@Chad - 这是什么浅拷贝?
-
@Arya,查看此问题及其答案:stackoverflow.com/questions/184710/…
标签: c++ c arrays pointers struct