Structures and Pointers in C++
Structures and Pointers in C++
The exam tests whether you can model records with struct, access members correctly, and use pointers safely for indirection and dynamic data.
Structures
- A
structgroups variables of different types under one name. Each member has its own type. - Declare:
struct Student { int roll; float marks; };- the semicolon after}is mandatory. - Access with the dot operator:
s1.roll = 12;. Structures can be nested and can form arrays. - Assignment between same-type structures copies all members.
Pointers
- A pointer stores an address.
int x = 5; int *p = &x;-&gives address,*dereferences. - For a structure pointer, use
->:p->rollis equivalent to(*p).roll. - Pointer arithmetic scales by the pointed-to type;
p + 1moves bysizeof(int)for anint*.
Worked example
struct Node { int data; Node *next; }; then Node n; Node *p = &n; p->data = 7; n.next = nullptr; Output of n.data is 7. Reasoning: p holds the address of n, so p->data writes into n.data. A self-referential next pointer is what makes linked structures possible.
Traps
- Missing semicolon after a
structdefinition. - Dereferencing an uninitialised or deleted pointer (undefined behaviour).
- Writing
p.datawhenpis a pointer; usep->data. - Confusing
*p++with(*p)++; precedence changes the meaning. - Returning the address of a local variable, which becomes dangling.