100.0k views
0 votes
Is it possible to copy individual fields of a compound type in C?

a) Yes, using memcpy()
b) No, fields can't be copied individually
c) Only with a direct assignment
d) Depends on the data type

User DaOgre
by
7.7k points

1 Answer

5 votes

Final answer:

The answer is c) Only with a direct assignment. Individual fields of a compound type in C, such as members of a struct, can be copied by directly assigning each field, which ensures the correct handling of the structure's memory layout.

Step-by-step explanation:

The question is: Is it possible to copy individual fields of a compound type in C? The correct answer is c) Only with a direct assignment. In C programming, you can indeed copy individual fields of a compound type, such as a struct, by using direct assignment to each field. The memcpy() function is not appropriate for copying individual fields because it is designed for copying blocks of memory and does not take into account the structures' alignment and padding issues which might differ between fields. Copying individual fields ensures that each assignment is made according to the field's type, thereby respecting the structure's memory layout. Here is an example of how you might copy the 'age' field from one 'Person' struct to another:
struct Person {
char name[50];
int age;
};
struct Person person1 = {.name = "Alice", .age = 30};
struct Person person2;
person2.age = person1.age; // Direct assignment of the individual field
As shown above, the 'age' field is copied from person1 to person2 using direct assignment without affecting other fields.

User Dorjay
by
8.0k points