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.

c
1#include <stdio.h>
2
3int main() {
4 // Array definition
5 int readings[5] = {100, 200, 300, 400, 500};
6
7 // Accessing (0-indexed)
8 int first = readings[0]; // 100
9
10 // Modifying
11 readings[1] = 250;
12
13 printf("First reading: %d\n", first);
14
15 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.

c
1#include <stdio.h>
2
3int main() {
4 // The compiler automatically adds the '\0' at the end for you
5 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);
11
12 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.

c
1#include <stdio.h>
2#include <string.h>
3
4int main() {
5 char name[] = "ESP32";
6
7 // 1. Get length (does NOT count the \0)
8 int len = strlen(name); // len = 5
9
10 // 2. Compare strings (returns 0 if they are exactly equal)
11 int cmp = strcmp(name, "ESP32"); // cmp = 0
12
13 // 3. Find substring (returns a pointer to the start of "SP32")
14 char *found = strstr(name, "SP");
15
16 if (cmp == 0) {
17 printf("Length of %s is %d\n", name, len);
18 }
19
20 return 0;
21}
Previous
Functions & Scope