Deepcopy: Difference between revisions

Added C implementation.
(Added Julia language)
(Added C implementation.)
Line 114:
86 51 50 43 82 76 13 78 33 45 11 35 84 25 80 36 33 81 43 24</lang>
 
=={{header|C}}==
===Structures without pointers===
Structures without pointers can be copied like ''standard'' C variables such as int, float, char etc. The level of nesting is irrelevant. As the following implementation shows, a simple assignment is enough :
<lang C>
/*Abhishek Ghosh, 15th November 2017*/
 
#include<stdio.h>
 
typedef struct{
int a;
}layer1;
 
typedef struct{
layer1 l1;
float b,c;
}layer2;
 
typedef struct{
layer2 l2;
layer1 l1;
int d,e;
}layer3;
 
void showCake(layer3 cake){
printf("\ncake.d = %d",cake.d);
printf("\ncake.e = %d",cake.e);
printf("\ncake.l1.a = %d",cake.l1.a);
printf("\ncake.l2.b = %f",cake.l2.b);
printf("\ncake.l2.l1.a = %d",cake.l2.l1.a);
}
 
int main()
{
layer3 cake1,cake2;
cake1.d = 1;
cake1.e = 2;
cake1.l1.a = 3;
cake1.l2.b = 4;
cake1.l2.l1.a = 5;
printf("Cake 1 is : ");
showCake(cake1);
cake2 = cake1;
cake2.l2.b += cake2.l2.l1.a;
printf("\nCake 2 is : ");
showCake(cake2);
return 0;
}
</lang>
Output:
<pre>
Cake 1 is :
cake.d = 1
cake.e = 2
cake.l1.a = 3
cake.l2.b = 4.000000
cake.l2.l1.a = 5
Cake 2 is :
cake.d = 1
cake.e = 2
cake.l1.a = 3
cake.l2.b = 9.000000
cake.l2.l1.a = 5
</pre>
===Structures with pointers===
Structures with pointers which are usually used to represent data structures such as Linked lists, Stacks, Trees, Graphs etc. have to be copied element by element. A simple assignment as in the above example will not be a copy at all. It will be two pointers pointing towards the same memory location.
<lang C>
/*Abhishek Ghosh, 15th November 2017*/
 
#include<stdlib.h>
#include<stdio.h>
 
typedef struct elem{
int data;
struct elem* next;
}cell;
 
typedef cell* list;
 
void addToList(list *a,int num){
list temp, holder;
if(*a==NULL){
*a = (list)malloc(sizeof(cell));
(*a)->data = num;
(*a)->next = NULL;
}
else{
temp = *a;
while(temp->next!=NULL)
temp = temp->next;
holder = (list)malloc(sizeof(cell));
holder->data = num;
holder->next = NULL;
temp->next = holder;
}
}
 
list copyList(list a){
list b, tempA, tempB, temp;
if(a!=NULL){
b = (list)malloc(sizeof(cell));
b->data = a->data;
b->next = NULL;
tempA = a->next;
tempB = b;
while(tempA!=NULL){
temp = (list)malloc(sizeof(cell));
temp->data = tempA->data;
temp->next = NULL;
tempB->next = temp;
tempB = temp;
tempA = tempA->next;
}
}
return b;
}
 
void printList(list a){
list temp = a;
while(temp!=NULL){
printf("%d,",temp->data);
temp = temp->next;
}
printf("\b");
}
 
int main()
{
list a,b;
int i;
for(i=1;i<=5;i++)
addToList(&a,i);
printf("List a is : ");
printList(a);
b = copyList(a);
free(a);
printf("\nList a destroyed, List b is : ");
printList(b);
return 0;
}
</lang>
Output:
<pre>
List a is : 1,2,3,4,5,
List a destroyed, List b is : 1,2,3,4,5,
</pre>
=={{header|C sharp}}==
<lang csharp>using System;
503

edits