Posted by yanib on 2025-03-16 08:51:58 |
Share: Facebook | Twitter | Whatsapp | Linkedin Visits: 223
A structure in C is a user-defined data type that allows you to group different types of data together under a single name. This is useful when you want to store multiple attributes (such as name, age, salary) of a person or object, but each attribute may be of different types (like string, integer, float, etc.).
In the above example:
struct employee
is the structure definition.name
, id
, and salary
are the members of the structure employee
, where name
is a string (char
array), id
is an integer, and salary
is a floating-point number.Array | Structure |
---|---|
1. An array is a collection of related data elements of the same type. | 1. A structure can have elements of different types. |
2. An array is a derived data type. | 2. A structure is a user-defined data type. |
3. Array name is a pointer to the first element. | 3. Structure name is not a pointer. |
You can pass structure members to a function in C in the same way as individual variables.
You can pass an array of structures to a function as an argument. Here's an example that works with an array of structures.
A union is similar to a structure, but it uses the same memory location for all its members. So, only one member can hold a value at any time.
In the above example:
student
has two members: roll
and marks
.Structure | Union |
---|---|
1. Takes more memory (separate memory is allocated for each member). | 1. Takes less memory (memory is shared by all members). |
2. All members can be accessed at any time. | 2. Only one member can be accessed at any time. |
3. Memory size is the sum of the sizes of all members. | 3. Memory size is the size of the largest member. |
Let me know if you need any further clarification!