π¦
STUDENT NOTES Β· C & C++ WEEK 3 OF 8
Arrays & the Missing Seatbelts π¦
C's train of boxes β faster than Python's lists, but with NO safety rails. Time to learn careful driving.
1Arrays β fixed-size trains
βοΈ
Chip: Declared with a size, indexed from 0 β and that size NEVER changes. No .append() in C; you ask for exactly the wagons you need, up front.
2Looping an array
3β οΈ The famous missing seatbelt
π
Bugly: 3 wagons. Ask for wagon 3 (the 4th!). Python throws IndexError. C⦠hehehe⦠C just READS WHATEVER MEMORY IS THERE:
π¦
Professor Hoot: Undefined behavior β maybe garbage, maybe a crash, maybe it "works" today and explodes at the demo. C trusts you completely. Be trustworthy.
4Strings β char arrays with a secret ending
βοΈ
Chip: A C string is a char array ending in an invisible \0 (the null terminator). That's how printf knows where to stop reading. strlen counts everything BEFORE it.
5Quick quiz! π§
int a[3] = {10, 20, 30}; β what does a[3] give in C?
π‘ C has no bounds checking. It reads whatever bytes sit past the array. The scariest β and most educational β bug in C.
char team[10] can safely hold a name of at mostβ¦
π‘ One slot always belongs to the invisible \0. Overfill it and you've invented a buffer overflow.
6Your mission π
Mission 1: Make an int array of 5 marks and print the total with a loop.
Mission 2: Store your name in a char array and print it with %s, then its length with strlen.
Mission 3: Read a[5] on a 3-element array ON PURPOSE (in onlinegdb). Observe the garbage. Feel the danger. Never do it again. π
Week 3 complete β you drive without seatbelts now. Carefully. π¦
Next: POINTERS. The chapter that makes C famous β and finally makes it click.
Go to Week 4: Pointers β