On a typical 64-bit system (char 1, int 4, double 8 bytes), find sizeof for struct A { char c; int i; char d; };, struct B { int i; char c; char d; }; and struct C { char c; double d; int i; };, and show how reordering C helps.
A structure groups related variables of different types under one name; a union overlays its members in the same memory; an enum names a set of integer constants. Member access, padding and sizeof, bit-fields and structure-versus-union are the exam favourites.
struct tag { members }; defines a type; storage is allocated only when a variable is declared. Members may have different types.. on a structure variable and -> through a pointer: p->x means (*p).x.s2 = s1 copies every member, arrays included) but not compared with ==.enum {A = 5, B, C} gives 5, 6, 7.unsigned day : 5; pack small values; you cannot take their address or make arrays of them.struct node *next;) — the building block of linked lists and trees.Members are reached with the dot operator ., as in s1.marks = 92.0f;. A structure can be initialised with a brace list in member order, and any members you leave out become zero. C99 added designated initialisers, which name the members and may list them in any order.
struct point { int x, y; };
struct point a = {3, 4}; /* x = 3, y = 4 */
struct point b = {7}; /* x = 7, y = 0 (rest zeroed) */
struct point c = {.y = 9, .x = 1}; /* C99 designated: x = 1, y = 9 */
struct point d;
d = a; /* OK: member-by-member copy */
/* if (d == a) ... error: no == for structures */
if (d.x == a.x && d.y == a.y) { /* compare member by member instead */ }=, passing to and returning from functions, taking the address &s, and sizeof.==, !=, < or arithmetic on whole structures. Compare member by member — memcmp is unreliable because padding bytes may hold different garbage.scanf("%d %19s", &s.roll, s.name); — no & for the char array.. sits at the highest precedence level with [], () and ->. So &s.roll means &(s.roll), and s.name[0] means (s.name)[0] — the first character of the name.A member can itself be a structure — a nested structure — reached with a chain of dots. An array of structures stores many records, each element a complete structure, so staff[2].salary is the salary of the third employee and staff[2].joined.year digs one level deeper.
#include <stdio.h>
struct date { int day, month, year; };
struct employee {
char name[20];
struct date joined; /* nested structure */
float salary;
};
int main(void)
{
struct employee staff[3] = { /* array of structures */
{"Anu", {12, 6, 2019}, 45000.0f},
{"Biju", { 1, 4, 2021}, 38000.0f},
{"Cini", {23, 9, 2016}, 52000.0f},
};
float total = 0;
for (int i = 0; i < 3; i++)
total += staff[i].salary;
printf("%s joined in %d\n", staff[2].name, staff[2].joined.year); /* Cini joined in 2016 */
printf("average salary %.2f\n", total / 3); /* average salary 45000.00 */
return 0;
}typedef creates an alias for an existing type, so you need not write struct everywhere: after typedef struct { int x, y; } Point; you can declare Point p, q;. It does not create a new type, only a new name, and it obeys scope rules. typedef also serves portability (the library's size_t is a typedef) and tames complicated declarations such as function pointers.
typedef char *String; String a, b; both a and b are char *. With #define String char * the same line expands to char * a, b; — only a is a pointer, and b is a plain char.A pointer to a structure holds the address of the whole record: struct student *p = &s1;. To reach a member through it you could write (*p).marks — the brackets are needed because . binds tighter than * — but C offers the shorthand arrow operator, p->marks. Without brackets, *p.marks would mean *(p.marks), which is an error because p is not a structure.
#include <stdio.h>
struct item { char name[10]; int qty; };
int main(void)
{
struct item stock[3] = {{"pen", 10}, {"ink", 5}, {"pad", 7}};
struct item *p = stock; /* points to stock[0] */
printf("%s %d\n", p->name, p->qty); /* pen 10 */
p++; /* advances by sizeof(struct item) bytes */
printf("%s %d\n", (*p).name, p->qty); /* ink 5 */
++p->qty; /* -> binds tighter: increments the qty */
printf("%d\n", stock[1].qty); /* 6 */
printf("%d\n", (p + 1)->qty); /* 7 (that is stock[2]) */
return 0;
}A structure can be passed to a function by value — the whole record is copied, changes stay local, and big structures cost time — or by address, where only a pointer is copied and the function can modify the original cheaply. Use const struct student * when the function only reads. A function may also return a structure, which is one way for C to return several values at once.
#include <stdio.h>
struct account { int id; double balance; };
void deposit(struct account *a, double amount) /* by address: changes the caller */
{
a->balance += amount;
}
double report(struct account a) /* by value: works on a copy */
{
a.balance = 0; /* no effect on the caller */
return a.balance;
}
struct account open_account(int id) /* returning a structure */
{
struct account a = {id, 500.0};
return a;
}
int main(void)
{
struct account acc = open_account(7);
deposit(&acc, 250.0);
report(acc);
printf("%d %.2f\n", acc.id, acc.balance); /* 7 750.00 */
return 0;
}| Expression | Meaning |
|---|---|
p->x | member x of the structure p points to; same as (*p).x |
++p->x | increments the member x (-> is applied before ++) |
p++->x | uses x of the current element, then moves p to the next element |
(++p)->x | moves p first, then reads x of the next element |
*p->s | first character of the string member s, i.e. *(p->s) |
&s.x | address of member x, i.e. &(s.x) |
Processors access memory fastest when a value sits at an address that is a multiple of its size — an int at a multiple of 4, a double at a multiple of 8. This is the value's alignment requirement. To honour it, the compiler inserts unused padding bytes between members, and also at the end, so that the total size is a multiple of the largest member alignment; otherwise the second element of an array of such structures would be misaligned.
| Offset | Contents | Why |
|---|---|---|
| 0 | c (1 byte) | the first member is always at offset 0 |
| 1–3 | padding (3 bytes) | i must start at a multiple of 4 |
| 4–7 | i (4 bytes) | an aligned int |
| 8 | d (1 byte) | a char can go anywhere |
| 9–11 | padding (3 bytes) | the total is rounded up to a multiple of 4 |
| Structure | Layout | sizeof |
|---|---|---|
struct { char c; int i; char d; } | 1 + 3 pad + 4 + 1 + 3 pad | 12 |
struct { int i; char c; char d; } | 4 + 1 + 1 + 2 pad | 8 |
struct { char a; char b; int c; } | 1 + 1 + 2 pad + 4 | 8 |
struct { char c; double d; int i; } | 1 + 7 pad + 8 + 4 + 4 pad | 24 |
struct { double d; int i; char c; } | 8 + 4 + 1 + 3 pad | 16 |
struct { short s; char c; int i; double d; } | 2 + 1 + 1 pad + 4 + 8 | 16 |
struct { char name[10]; int qty; } | 10 + 2 pad + 4 | 16 |
offsetof(type, member) from <stddef.h> reports a member's offset, so you can check a layout. Compilers also offer ways to drop padding — #pragma pack(1) or GCC's __attribute__((packed)) — which shrink struct { char c; int i; char d; } to 6 bytes at the cost of slower, or on some processors faulting, unaligned access. These are compiler extensions, not standard C.
A bit-field member occupies a stated number of bits rather than whole bytes, so several small values can share one storage unit — useful for flags, packed dates and hardware registers. The width is written after a colon:
#include <stdio.h>
struct date {
unsigned int day : 5; /* 0..31 needs 5 bits */
unsigned int month : 4; /* 0..15 needs 4 bits */
unsigned int year : 12; /* 0..4095 needs 12 bits */
}; /* 21 bits: fits in one 4-byte unit */
struct flags {
unsigned int ready : 1;
unsigned int error : 1;
unsigned int : 2; /* unnamed: 2 bits of padding */
unsigned int mode : 3;
};
int main(void)
{
struct date d = {25, 12, 2026};
printf("%u/%u/%u size %zu\n", d.day, d.month, d.year, sizeof d); /* 25/12/2026 size 4 */
struct flags f = {0};
unsigned int nine = 9;
f.mode = nine; /* 9 does not fit in 3 bits: stored as 9 % 8 = 1 */
printf("%u\n", f.mode); /* 1 */
return 0;
}unsigned int, signed int, int and (C99) _Bool; others are implementation-defined. Whether a plain int bit-field is signed is also implementation-defined, so prefer unsigned.&d.day is an error), so scanf cannot read into one directly, and there are no arrays of bit-fields or pointers to them.A union is declared like a structure, but all its members share the same memory, starting at the same address. Its size is that of the largest member, rounded up to the union's alignment. Only one member holds a meaningful value at a time — the one written most recently — because writing any member overwrites the same bytes.
#include <stdio.h>
union value {
int i;
float f;
char s[10];
}; /* largest member 10 bytes -> sizeof 12 */
int main(void)
{
union value v;
printf("%zu\n", sizeof v); /* 12: 10 rounded up to int alignment (4) */
v.i = 65;
printf("%c\n", v.s[0]); /* 'A' on a little-endian machine: the low */
/* byte of 65 is stored first */
v.f = 2.5f; /* overwrites the same bytes; v.i is now meaningless */
printf("%.1f\n", v.f); /* 2.5 */
return 0;
}Unions save memory when a value may be one of several kinds but never several at once. The standard pattern is a tagged union: a structure that holds an enum 'tag' recording which member is active, plus the union itself. Unions are also used to inspect the bytes of a value — for example to test the machine's byte order: after union { unsigned int x; unsigned char b[4]; } u; u.x = 0x12345678; a little-endian machine (x86, ARM) has u.b[0] == 0x78.
#include <stdio.h>
enum kind { INT_VAL, REAL_VAL };
struct number {
enum kind tag; /* records which member of u is active */
union { int i; double d; } u;
};
void print(struct number n)
{
if (n.tag == INT_VAL) printf("%d\n", n.u.i);
else printf("%.2f\n", n.u.d);
}
int main(void)
{
struct number a = {INT_VAL, {.i = 42}};
struct number b = {REAL_VAL, {.d = 3.75}};
print(a); /* 42 */
print(b); /* 3.75 */
return 0;
}union value v = {65};); use a designated initialiser such as {.f = 2.5f} for any other.| Aspect | Structure | Union |
|---|---|---|
| Keyword | struct | union |
| Memory | each member has its own storage | all members share one storage area |
| Size | ≥ the sum of the member sizes (plus padding) | the size of the largest member (plus padding) |
| Values held at once | all members | only the most recently written member |
| Member offsets | increase in declaration order | every member at offset 0 |
| Initialisation with { } | all members, in order | the first member only (or one designated member) |
| Typical use | records: student, employee, list node | variant data, saving memory, viewing raw bytes |
An enumeration defines a set of named integer constants: enum color { RED, GREEN, BLUE }; makes RED 0, GREEN 1 and BLUE 2. You may assign values explicitly; every constant without one is one more than the previous, and values may repeat. Enum constants have type int, and an enum variable usually has the size of an int.
#include <stdio.h>
enum level { LOW = 1, MEDIUM, HIGH = 10, CRITICAL }; /* 1 2 10 11 */
enum days { SUN, MON, TUE = 5, WED, THU = 2, FRI, SAT }; /* 0 1 5 6 2 3 4 */
int main(void)
{
enum level lv = HIGH;
printf("%d %d %d %d\n", LOW, MEDIUM, HIGH, CRITICAL);
printf("%d %d %d %d %d %d %d\n", SUN, MON, TUE, WED, THU, FRI, SAT);
switch (lv) { /* enums pair naturally with switch */
case LOW: puts("relax"); break;
case HIGH: puts("act now"); break; /* printed */
default: puts("watch");
}
printf("%zu\n", sizeof lv); /* 4 (an int) on common compilers */
return 0;
}Enums make code self-documenting — if (state == RUNNING) instead of if (state == 2) — and give debuggers symbolic names. C does little checking: an enum variable may be assigned any int, so enum color c = 7; compiles. Compared with #define RED 0, enum constants obey scope rules and are numbered automatically; both are genuine constant expressions, usable as case labels.
A self-referential structure contains a pointer to its own type: struct node { int data; struct node *next; };. It cannot contain a member of its own type — that would need infinite size, and the type is still incomplete inside its own braces — but a pointer has a fixed size (8 bytes on 64-bit), so the definition is fine. Chaining such nodes through their pointers builds linked lists, stacks and queues, and with two pointers per node, binary trees.
#include <stdio.h>
struct node {
int data;
struct node *next; /* pointer to the same type: allowed */
/* struct node child; error: incomplete type (infinite size) */
};
typedef struct tnode { /* keep the tag: the typedef name does */
int key; /* not exist yet inside the braces */
struct tnode *left, *right;
} TreeNode;
int main(void)
{
struct node c = {30, NULL}, b = {20, &c}, a = {10, &b}; /* a -> b -> c */
for (struct node *p = &a; p != NULL; p = p->next)
printf("%d ", p->data); /* 10 20 30 */
printf("\n%zu %zu\n", sizeof(struct node), sizeof(TreeNode)); /* 16 24 on 64-bit */
return 0;
}Try the problem first, then reveal the working one step at a time.
On a typical 64-bit system (char 1, int 4, double 8 bytes), find sizeof for struct A { char c; int i; char d; };, struct B { int i; char c; char d; }; and struct C { char c; double d; int i; };, and show how reordering C helps.
On a typical 64-bit system (int 4, double 8 with 8-byte alignment), find sizeof for union U { int i; double d; char s[12]; };. Then, for union { int i; char s[10]; } u; u.i = 65;, what does printf("%c", u.s[0]) print on a little-endian PC?
Give the value of every constant in enum { A, B = 4, C, D = B + 5, E }; and in enum level { LOW = 1, MEDIUM, HIGH = 10, CRITICAL };.
With struct item { char name[10]; int qty; } stock[3] = {{"pen", 10}, {"ink", 5}, {"pad", 7}}; struct item *p = stock + 1;, evaluate in order: p->name, ++p->qty, (++p)->qty, p - stock, and the byte distance (char *)p - (char *)stock on a 64-bit system.
Compute sizeof for struct E { short s; char c; int i; double d; }; on a 64-bit system, both normally and under #pragma pack(1).
What does this print? struct bf { unsigned a : 3; unsigned b : 2; } x; unsigned nine = 9, five = 5; x.a = nine; x.b = five; printf("%u %u", x.a, x.b);
Given typedef int *IP; and #define DP int *, which of a, b, c, d are pointers after IP a, b; DP c, d;? Explain.
Write a function that gives every employee in an array a 10% raise through a pointer parameter, and show the call for an array of 3 employees.
For struct node { int data; struct node *next; };, explain why struct node { int data; struct node next; }; is rejected, and find sizeof(struct node) on 32-bit and 64-bit systems.
p->x equals (*p).x, but *p.x means *(p.x); and ++p->x increments the member, not the pointer.s2 = s1) but not compared with == — compare members one by one.typedef char *str; str a, b; makes both pointers, while #define str char * makes only the first one a pointer.10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.
struct item *p pointing at a structure, which operator reaches that structure's members through p?