我将在以下两个代码中执行同样的操作。
在代码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?)
}
b.p
是从a.p
进行浅拷贝。 - Chadb = a
这一行,所以我删除了我的评论。 - wkl