C Refresher
Arrays & Strings
In Python or JavaScript, lists and strings are highly flexible, built-in objects that manage their own memory. In C, arrays and strings are just raw, consecutive blocks of memory.
Arrays
An array is a collection of variables of the same type stored right next to each other in memory.
1#include <stdio.h>23int main() {4 // Array definition5 int readings[5] = {100, 200, 300, 400, 500};6 7 // Accessing (0-indexed)8 int first = readings[0]; // 1009 10 // Modifying11 readings[1] = 250;12 13 printf("First reading: %d\n", first);1415 return 0;16}Buffer Overflows
C does not check array bounds. If you have an array of 5 items, and you try to write to readings[10] = 500;, C will happily overwrite whatever data happens to be living in that memory location. You must keep track of array sizes yourself.
Strings in C
C does not have a "String" type.
In C, a string is simply an Array of Characters, with a very specific rule: The last character in the array must be the "Null Terminator" (\0).
The Null Terminator
The Null Terminator is a byte with the value 0. It tells functions like printf where the string ends. Without it, printf would keep reading and printing random memory until it crashed.
1#include <stdio.h>23int main() {4 // The compiler automatically adds the '\0' at the end for you5 char name[] = "ESP32"; 6 7 // The array "name" is actually {'E', 'S', 'P', '3', '2', '\0'} 8 // It takes up 6 bytes of memory, not 5!9 10 printf("Device: %s\n", name);1112 return 0;13}String Manipulation Functions
Because strings are just arrays, you cannot use the == operator to compare them, nor the + operator to join them. You must use functions from the <string.h> library.
1#include <stdio.h>2#include <string.h>34int main() {5 char name[] = "ESP32";6 7 // 1. Get length (does NOT count the \0)8 int len = strlen(name); // len = 59 10 // 2. Compare strings (returns 0 if they are exactly equal)11 int cmp = strcmp(name, "ESP32"); // cmp = 012 13 // 3. Find substring (returns a pointer to the start of "SP32")14 char *found = strstr(name, "SP"); 1516 if (cmp == 0) {17 printf("Length of %s is %d\n", name, len);18 }1920 return 0;21}
