Structure Layout & Padding

struct S1 { char a; int b; double c; char d; };  // 24 bytes
struct S2 { double c; int b; char a; char d; }; // 16 bytes
// Same fields, different layout + padding!
char int double padding

Note: Exact sizes/alignments depend on the system. Order members from largest to smallest to minimize padding.

What's a Pointer?

Instead of holding a value, it holds a memory address.

Normal Variable:

int score = 95;
Address: 0x7ffc...A0
Value:   95

Pointer Variable:

int* score_ptr = &score;
Address: 0x7ffc...B8
Value:   0x7ffc...A0
  • `&` is the "address-of" operator.
  • `*` is used to declare a pointer.

Pointer Arithmetic: Moving the Cursor

int a[8] {2,4,6,8,10,12,14,16};
int* p = &a[0];
// p++ moves to next element, jumping sizeof(int) bytes

Member Access: Dot vs. Arrow

Player p1 = {"Hero", 100, 0};
Player* player_ptr = &p1;

p1.score += 10;        // Dot for object
player_ptr->score += 10; // Arrow for pointer
Player p1 name health score Player* player_ptr

`ptr->member` is just convenient shorthand for `(*ptr).member`.

Array of Structs — Pointer Stride

struct Pair { int x; int y; }; // sizeof(Pair) is 8 bytes
Pair a[5]{{1,2},{3,4},{5,6},{7,8},{9,10}};
Pair* p = a;   // p++ jumps by 8 bytes

The True Power: Linked Data Structures

struct Node { int data; Node* next; };
// A Node can point to another Node, forming a chain!
Node* head = ...;   // Walk the chain until next is nullptr

Mini‑Quiz Q1

Q1. Given `Player* ptr`, how do you correctly access the player's health?



Mini‑Quiz Q2

Q2. To minimize padding for `{char, int, double}`, which order is best on a typical 64-bit system?



Summary (Part 1)

  • `struct` groups related data into a new, custom type.
  • Pass structs by `const` reference (`const T&`) for efficient, safe, read-only access.
  • Lambdas `[](){}` are convenient inline functions, great for algorithms like `std::sort`.

Summary (Part 2)

  • Structure member order affects padding and total size.
  • A pointer stores a memory address; use `->` to access members via a pointer.
  • Pointers enable dynamic data structures like linked lists.