Structures and Unions in C
Structures and unions are user-defined data types in C that allow storing multiple related variables under a single name. They help organize complex data efficiently.
Structures in C
A structure is a collection of different data types grouped together under one name.
Declaring a Structure
A structure is defined using the struct
keyword.
struct Student {
char name[50];
int age;
float marks;
};
Accessing Structure Members
Structure members are accessed using the dot (.
) operator.
struct Student s1;
s1.age = 20;
s1.marks = 85.5;
Initializing Structures
Structures can be initialized at the time of declaration.
struct Student s1 = {"John Doe", 20, 85.5};
Example Program
#include <stdio.h>
struct Student {
char name[50];
int age;
float marks;
};
int main() {
struct Student s1 = {"Alice", 22, 90.5};
printf("Name: %s\n", s1.name);
printf("Age: %d\n", s1.age);
printf("Marks: %.2f\n", s1.marks);
return 0;
}
Unions in C
A union is similar to a structure but uses shared memory, meaning only one member can store a value at a time.
Declaring a Union
A union is defined using the union
keyword.
union Data {
int i;
float f;
char str[20];
};
Accessing Union Members
Since all members share the same memory, changing one affects others.
union Data d;
d.i = 10;
printf("%d", d.i);
Example Program
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data d;
d.i = 10;
printf("Integer: %d\n", d.i);
d.f = 20.5;
printf("Float: %.2f\n", d.f);
return 0;
}
Difference Between Structure and Union
Feature | Structure | Union |
---|---|---|
Memory | Each member has separate memory | All members share the same memory |
Size | Sum of all members' sizes | Size of the largest member |
Usage | Used when storing multiple independent values | Used when only one value is needed at a time |
If you have any questions, feel free to ask. Thank you for reading!
If you have any query or question, please contact through below form. Our team will be in touch with you soon.
Please provide your valueable feedback or suggession as well.