CC · Lesson 8 of 8

C Cheatsheet

Pointers, memory, strings, and structs on one page.

C
// ── Basics ──────────────────────────────
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    int x = 42;
    double pi = 3.14;
    char c = 'A';
    printf("%d %f %c %s\n", x, pi, c, "text");
    // %d int  %f double  %c char  %s string  %p pointer
    // %zu size_t  %ld long  %x hex
    return 0;
}

// ── Control flow ────────────────────────
if (x > 10) { } else if (x > 5) { } else { }
for (int i = 0; i < 5; i++) { }
while (cond) { }
do { } while (cond);
switch (n) { case 1: ...; break; default: ...; }

// ── Arrays & strings ────────────────────
int nums[5] = {3, 1, 4, 1, 5};
int len = sizeof(nums) / sizeof(nums[0]);
char s[] = "hello";              // char array + '\0'
strlen(s); strcmp(a, b); strcpy(dst, src);
strncpy(dst, src, n);            // bounded (safer)
snprintf(buf, sizeof buf, "%d", x);  // int -> string
C
// ── Pointers ────────────────────────────
int x = 42;
int *p = &x;         // p holds x's address
*p = 10;             // dereference: x is now 10
int arr[3] = {1, 2, 3};
int *a = arr;        // arrays decay to pointers
a[1] == *(a + 1);    // same thing

void grow(int *n) { (*n)++; }   // "pass by reference"
grow(&x);

// ── Heap memory ─────────────────────────
int *buf = malloc(10 * sizeof(int));
if (buf == NULL) { /* always check */ }
buf = realloc(buf, 20 * sizeof(int));
free(buf);            // exactly once, then don't touch
buf = NULL;           // habit that prevents use-after-free

char *copy = strdup(s);   // malloc + strcpy
free(copy);

// ── Structs ─────────────────────────────
struct Point { int x, y; };
typedef struct { char name[50]; int age; } Dog;
Dog d = { "Rex", 3 };
d.age = 4;
Dog *pd = &d;
pd->age = 5;          // arrow for pointer access

// ── Files ───────────────────────────────
FILE *f = fopen("data.txt", "r");   // "w" write, "a" append
if (f) {
    char line[256];
    while (fgets(line, sizeof line, f)) { }
    fclose(f);
}

// gcc -Wall -Wextra -std=c17 main.c -o app
// valgrind ./app       <- finds leaks & bad memory access