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!
Note: Exact sizes/alignments depend on the system. Order members from largest to smallest to minimize padding.
Instead of holding a value, it holds a memory address.
Normal Variable:
int score = 95;
→
0x7ffc...A0
95
Pointer Variable:
int* score_ptr = &score;
→
0x7ffc...B8
0x7ffc...A0
int a[8] {2,4,6,8,10,12,14,16};
int* p = &a[0];
// p++ moves to next element, jumping sizeof(int) bytes
Player p1 = {"Hero", 100, 0};
Player* player_ptr = &p1;
p1.score += 10; // Dot for object
player_ptr->score += 10; // Arrow for pointer
`ptr->member` is just convenient shorthand for `(*ptr).member`.
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
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
Q1. Given `Player* ptr`, how do you correctly access the player's health?
Q2. To minimize padding for `{char, int, double}`, which order is best on a typical 64-bit system?