对于一个指针进行解引用,然后复制给另一个引用,那么效果等价于进行了浅复制。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <iostream>
using namespace std;
struct node{
int data;
char name[10];
};
int main(){
int pid=fork();
if(pid==0){
printf("child\n");
}
else{
printf("parent\n");
struct node * node1=(struct node*)malloc(sizeof(struct node));
node1->data=12;
strcpy(node1->name,"world");
printf("%d %s\n",node1->data,node1->name);
struct node node2=*(node1);
node2.data=13;
cout<<"node1 data is:"<<node1->data<<" name is:"<<node1->name<<endl;
cout<<"node2 data is:"<<node2.data<<" name is:"<<node2.name<<endl;
}
return 0;
}
上面程序的运行结果为:
child
parent
12 world
node1 data is:12 name is:world
node2 data is:13 name is:world
本文通过一个C++程序示例介绍了如何对结构体进行浅复制,并展示了浅复制的效果。程序创建了一个包含整型和字符数组的结构体实例,对其进行了解引用并赋值给另一个结构体变量,修改后验证了两者共享同一字符数组。
10万+

被折叠的 条评论
为什么被折叠?



