C Structures and Unions
A struct groups variables of different types under one name.
#include <stdio.h>
#include <string.h>
struct Student {
int roll;
char name[20];
float cgpa;
};
int main() {
struct Student s1 = {1, "Asha", 8.9};
struct Student *p = &s1;
strcpy(p->name, "Asha K"); // -> for pointer access
printf("%d %s %.1f\n", s1.roll, s1.name, p->cgpa);
return 0;
}
1 Asha K 8.9
Structure vs Union
| Structure | Union |
|---|---|
| Each member has its own memory | All members share the same memory |
| Size ≥ sum of members (plus padding) | Size = largest member |
| All members usable at once | Only one member valid at a time |
union Data { int i; float f; char c; };
printf("%zu\n", sizeof(union Data));
4
Track your progress through the C course