Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Notes › C

Structures and Unions in C

Structures — grouping related data

A struct bundles variables of different types into one record.

struct Student {
    int roll;
    char name[30];
    float cgpa;
};

struct Student s1 = {1, "Asha", 8.4f};
struct Student s2;
s2.roll = 2;
strcpy(s2.name, "Ravi");     // arrays can't be assigned with =
s2.cgpa = 7.9f;
printf("%s %.1f\n", s1.name, s1.cgpa);

typedef — a shorter name

typedef struct Student Student;   // now "Student" alone means "struct Student"

typedef struct {
    int x, y;
} Point;

Point p = {3, 4};
Point q = p;                 // structs can be copied with = (member-wise copy)

Arrays of structures

Student list[3] = {{1, "A", 8.1f}, {2, "B", 9.0f}, {3, "C", 7.5f}};
float best = 0;
for (int i = 0; i < 3; i++) if (list[i].cgpa > best) best = list[i].cgpa;

Pointers to structures and ->

Student s = {1, "Asha", 8.4f};
Student *ptr = &s;
printf("%d\n", ptr->roll);     // same as (*ptr).roll
ptr->cgpa = 9.1f;

Pass large structs to functions by pointer to avoid copying them:

void raise(Student *st) { st->cgpa += 0.1f; }
raise(&s);

Self-referential structures

A struct can contain a pointer to its own type — the basis of linked lists and trees.

typedef struct Node {
    int data;
    struct Node *next;
} Node;

See Linked List.

Structure padding and alignment

The compiler may add unused bytes so each member starts at an address that suits its size — this makes memory access faster.

struct A { char c; int i; char d; };   // 1 + 3 (pad) + 4 + 1 + 3 (pad) = 12 bytes
struct B { int i; char c; char d; };   // 4 + 1 + 1 + 2 (pad) = 8 bytes

Same members, different order, different size. Put larger members first to reduce padding. sizeof(struct A) is 12 on most compilers, not 6.

Unions — one memory, many types

All members share the same memory; the size is the size of the largest member. Only one member holds a meaningful value at a time.

union Value {
    int i;
    float f;
    char str[8];
};
union Value v;
v.i = 65;
printf("%d\n", v.i);      // 65
v.f = 3.5f;               // overwrites the same bytes — v.i is now meaningless
printf("%zu\n", sizeof(v));   // 8 (the char[8])
struct union
Memory sum of members (+ padding) size of the largest member
Members used at once all one
Use records saving memory, variant types, reading the bytes of a value

Tagged union — store which member is valid:

typedef struct {
    enum { INT, FLOAT } type;
    union { int i; float f; } data;
} Number;

enum — named integer constants

enum Day { MON = 1, TUE, WED };     // TUE = 2, WED = 3
enum Day today = TUE;

Bit fields — pack flags into bits

struct Flags {
    unsigned int isAdmin : 1;
    unsigned int isVerified : 1;
    unsigned int level : 3;          // values 0–7
};

Interview one-liners

More C notes