Does a compound literal delete any previous fields?

Viewed 31

If I have the following code:

struct Person *person = malloc(sizeof (struct Person));
person->name = "Ed";
*person = (struct Person) {.age=40, .country="GB"};

Would the third statement wipe out the name? If so, is there any way to ignore or inherit any existing fields when using a compound literal, or does it wipe out all previous fields and recreate it from whatever was supplied (nullifying anything that wasn't supplied)?

1 Answers

When assigning directly to a struct, all fields are replaced with the corresponding field of the value on the right side of the assignment.

Whether the right hand side is a compound literal or a named object, the effect is the same. So this:

person = (struct Person) {.age=40, .country="GB"};

Assigns the same values to person as this:

struct Person person2 = {.age=40, .country="GB"};
person = person2;

Where the name field in both cases will be set to NULL as it is not explicit initialized in the compound literal or in the named object.

Note however that any padding bytes need not be the same after the copy:

Does struct assignment guarantee padding to also be equal

Related