If by “shallow copy” you mean that after assigning a struct containing an array, the array will point to the original data of the struct , and then: it cannot. Each element of the array must be copied to a new struct . A shallow copy appears in the picture if your structure has pointers. If this is not the case, you cannot make a shallow copy.
When you assign a value to a struct containing an array for some value, it cannot execute a shallow copy, as that means assigning to an array, which is illegal. So, the only copy you get is a deep copy.
Consider:
#include <stdio.h> struct data { char message[6]; }; int main(void) { struct data d1 = { "Hello" }; struct data d2 = d1; /* struct assignment, (almost) equivalent to memcpy(&d2, &d1, sizeof d2) */ /* Note that it illegal to say d2.message = d1.message */ d2.message[0] = 'h'; printf("%s\n", d1.message); printf("%s\n", d2.message); return 0; }
The above text will print:
Hello hello
If, on the other hand, your struct had a pointer, the struct assignment will only copy pointers that are a “shallow copy”:
#include <stdio.h> #include <stdlib.h> #include <string.h> struct data { char *message; }; int main(void) { struct data d1, d2; char *str = malloc(6); if (str == NULL) { return 1; } strcpy(str, "Hello"); d1.message = str; d2 = d1; d2.message[0] = 'h'; printf("%s\n", d1.message); printf("%s\n", d2.message); free(str); return 0; }
The above text will print:
Hello hello
In general, a given struct T d1, d2; d2 = d1; equivalent to memcpy(&d2, &d1, sizeof d2); but if the structure has padding, it may or may not be copied.
Edit: In C, you cannot assign arrays . Given:
int data[10] = { 0 }; int data_copy[10]; data_copy = data;
is illegal. So, as I said above, if you have an array in a struct , the purpose of the structure is to copy the data elements in the array. You do not get a shallow copy in this case: it makes no sense to apply the term "shallow copy" to this case.