From my understanding there is no actual "Shallow" copy or "Deep copy" inbuilt in C.
Some answer you may find are right but misleading if you think in an OOP perspective
In C, there is only one inbuilt copy technique when using the '=' operator, Data copy
C stores the metadata of a structure in the RAM and makes sure that once a struct is created, it's size will not change and the variables can be accessed from specific parts of the allocated memory
When you use the '=' operator, it only copies the data stored in the structure but by bit into another structure since they have same size.
Statically allocated variables and arrays in a struct have a fixed size and are stored completely within the struct's allocated memory. Dynamically allocated variables are all pointers. Pointers variables are statically allocated memory equivalent to an unsigned long int.
When you have a pointer in a struct, it only stored the address, the memory it points to, aka, the dynamically allocated location, the struct doesn't actually have any information that the pointer is pointing to a memory. It is the OS and the Complier that keeps track of dynamically allocated memory.
For example:
#include <stdio.h>
#include<stdlib.h>
struct Foo
{
int value_1;
int *value_2;
int value_3[3];
}S1,S2;
void print(struct Foo S)
{
printf("%d,%d,%d,%d,%d\n",S.value_1,*(S.value_2),S.value_3[0],S.value_3[1],S.value_3[2]);
}
int main()
{
S1.value_1=43;
S1.value_2=(int*)malloc(sizeof(int));
*(S1.value_2)=55;
S1.value_3[0]=101;
S1.value_3[1]=102;
S1.value_3[2]=103;
printf("S1:");
print(S1);
S2=S1;
printf("S2:");
print(S2);
S1.value_1=4300;
*(S1.value_2)=5500;
S1.value_3[0]=10100;
S1.value_3[1]=10200;
S1.value_3[2]=10300;
printf("\nAfter Altering\n");
printf("S1:");
print(S1);
printf("S2:");
print(S2);
return 0;
}
Output:
S1:43,55,101,102,103
S2:43,55,101,102,103
After Altering
S1:4300,5500,10100,10200,10300
S2:43,5500,101,102,103
In short, copying in C has 2 behaviours:
- For dynamically allocated variables, aka pointers, Shallow Copy is
used
- For statically allocated Variables or arrays, Deep copy is used
Additionally, if you were to make a pointer to a structure variable(not newly allocated), as long as the memory is within scope, it would act as a like a reference, any change made using either the normal variable or the structure pointer would result in both reflecting the same.
int a=20;
Foo S1,*S2;
S2=&S1;
S1.value1=10;
S1.value2=&a;
S1.value3[0]=101;
S1.value3[1]=102;
S1.value3[2]=103;
S2->value1=15;
In the above case, it doesn't matter which one we try to manipulate the values, since both affect the same physical memory
When you copy pointers as pointers/addresses, a shallow copy occurs
When you copy the value from a pointer to another variable/pointer , it behaves like copying between 2 non-pointers
->
,S2 = *S1
, etc...). The result will be exactly the same. – Afb