C Structures and Unions

A struct groups variables of different types under one name.

C
#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

StructureUnion
Each member has its own memoryAll members share the same memory
Size ≥ sum of members (plus padding)Size = largest member
All members usable at onceOnly one member valid at a time
C
union Data { int i; float f; char c; };
printf("%zu\n", sizeof(union Data));
4
Track your progress through the C course