C Cheatsheet
Arrays and Strings
Use this C reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Array Declaration and Initialization
// Fixed-size arrays — size must be a constant expression (before C99) int arr[5]; // uninitialized int arr2[5] = {1, 2, 3, 4, 5}; // fully initialized int arr3[5] = {1, 2}; // partially: {1, 2, 0, 0, 0} int arr4[] = {1, 2, 3}; // size inferred: 3 elements int arr5[5] = {0}; // all zeros int arr6[5] = {}; // C23: all zeros // Designated initializers (C99+) int arr7[5] = {[0]=10, [4]=50}; // rest are 0
Array Access and Size
int arr[] = {10, 20, 30, 40, 50}; int first = arr[0]; // 10 int last = arr[4]; // 50 arr[2] = 99; // modify element // Element count int len = sizeof(arr) / sizeof(arr[0]); // 5 // ONLY works on actual array, not pointer! // Arrays decay to pointer to first element when passed to functions // sizeof(pointer) != sizeof(array)
Multidimensional Arrays
int mat[3][4]; // 3 rows, 4 columns int mat2[2][3] = {{1,2,3},{4,5,6}}; int mat3[2][3] = {1,2,3,4,5,6}; // same, flattened init mat[1][2] = 99; // row 1, col 2 // Iterate for (int r = 0; r < 2; r++) for (int c = 0; c < 3; c++) printf("%d ", mat2[r][c]); // 3D int cube[2][3][4]; // Storage is row-major (C) — mat[i][j] and mat[i][j+1] are adjacent
Variable-Length Arrays (C99+, optional C11+)
int n = 10; int arr[n]; // VLA: size determined at runtime arr[0] = 5; // VLA function parameter void process(int n, int arr[n]); void print_matrix(int rows, int cols, int m[rows][cols]);
VLAs are optional in C11/C17 (
__STDC_NO_VLA__). Avoid large VLAs on the stack — no overflow protection.
String Literals and char Arrays
C strings are null-terminated arrays of char.
char s1[] = "hello"; // {'h','e','l','l','o','\0'} — writable copy char *s2 = "hello"; // pointer to string literal — do NOT modify // Literal is read-only; s1 is a mutable copy s1[0] = 'H'; // ok // s2[0] = 'H'; // undefined behavior // Size sizeof(s1) // 6 (including '\0') strlen(s1) // 5 (excluding '\0')
<string.h> Functions
| Function | Description | Example |
|---|---|---|
strlen(s) | Length (excluding \0) | strlen("hi") → 2 |
strcpy(dst, src) | Copy string | strcpy(buf, "hello") |
strncpy(dst, src, n) | Copy at most n chars | strncpy(buf, src, sizeof buf - 1) |
strcat(dst, src) | Concatenate onto dst | strcat(s, " world") |
strncat(dst, src, n) | Concatenate at most n chars | strncat(s, src, 5) |
strcmp(a, b) | Compare: <0, 0, >0 | if (!strcmp(a, b)) |
strncmp(a, b, n) | Compare at most n chars | strncmp(a, b, 3) |
strchr(s, c) | First occurrence of char | strchr("hello", 'l') |
strrchr(s, c) | Last occurrence of char | strrchr("hello", 'l') |
strstr(hay, needle) | Find substring | strstr(s, "lo") |
strtok(s, delim) | Tokenize (modifies string) | strtok(s, " ,") |
strtok_r(s, d, &sv) | Thread-safe tokenize | POSIX |
strdup(s) | Heap-copy of string (POSIX/C23) | char *c = strdup(s) |
strndup(s, n) | Heap-copy, at most n chars (POSIX) | |
sprintf(buf, fmt, ...) | Format to string | sprintf(buf, "%d", 42) |
snprintf(buf, n, fmt, ...) | Format with size limit (safe) | snprintf(buf, sizeof buf, "%d", n) |
sscanf(s, fmt, ...) | Parse from string | sscanf(s, "%d %d", &a, &b) |
#include <string.h> char buf[64]; strcpy(buf, "Hello"); strcat(buf, ", World"); printf("%zu\n", strlen(buf)); // 12 // Safe string copy pattern strncpy(dst, src, sizeof dst - 1); dst[sizeof dst - 1] = '\0'; // ensure null termination // snprintf is the safe format-into-buffer snprintf(buf, sizeof buf, "x=%d, y=%d", x, y);
<string.h> Memory Functions
| Function | Description |
|---|---|
memcpy(dst, src, n) | Copy n bytes (no overlap) |
memmove(dst, src, n) | Copy n bytes (safe with overlap) |
memset(s, c, n) | Fill n bytes with value c |
memcmp(a, b, n) | Compare n bytes |
memchr(s, c, n) | Find first byte c in n bytes |
memset(arr, 0, sizeof arr); // zero out array memcpy(dst, src, n * sizeof(int)); // copy array memmove(arr+1, arr, 4 * sizeof(int)); // shift elements right (overlap safe) int eq = (memcmp(a, b, len) == 0); // compare byte-for-byte
<ctype.h> Character Classification
| Function | True when |
|---|---|
isalpha(c) | letter (a-z, A-Z) |
isdigit(c) | digit (0-9) |
isalnum(c) | letter or digit |
isspace(c) | whitespace (space, tab, newline, ...) |
isupper(c) | uppercase letter |
islower(c) | lowercase letter |
isprint(c) | printable character |
ispunct(c) | punctuation |
iscntrl(c) | control character |
tolower(c) | convert to lowercase |
toupper(c) | convert to uppercase |
#include <ctype.h> char ch = 'A'; if (isalpha(ch)) printf("letter\n"); char lower = tolower(ch); // 'a' // Uppercase a string for (char *p = s; *p; p++) *p = toupper((unsigned char)*p); // Cast to unsigned char — undefined behavior otherwise for negative chars
String Conversion (<stdlib.h>)
| Function | Description |
|---|---|
atoi(s) | string → int (no error checking) |
atol(s) | string → long |
atof(s) | string → double |
strtol(s, &end, base) | string → long (with error detection) |
strtoul(s, &end, base) | string → unsigned long |
strtoll(s, &end, base) | string → long long |
strtod(s, &end) | string → double |
strtof(s, &end) | string → float |
#include <stdlib.h> // Robust integer parse char *end; errno = 0; long val = strtol("42abc", &end, 10); if (end == "42abc") { /* no digits */ } if (*end != '\0') { /* trailing garbage */ } if (errno == ERANGE){ /* overflow */ } // int to string char buf[32]; snprintf(buf, sizeof buf, "%d", 42);
Array Algorithms (using <stdlib.h>)
// qsort — compare function returns negative/zero/positive int cmp_int(const void *a, const void *b) { int x = *(const int *)a; int y = *(const int *)b; return (x > y) - (x < y); // avoids subtraction overflow } int arr[] = {5, 2, 8, 1, 9, 3}; qsort(arr, 6, sizeof(int), cmp_int); // arr: {1, 2, 3, 5, 8, 9} // bsearch — array must be sorted; returns pointer or NULL int key = 5; int *found = bsearch(&key, arr, 6, sizeof(int), cmp_int); if (found) printf("found: %d\n", *found); // Reverse an array for (int lo = 0, hi = len-1; lo < hi; lo++, hi--) { int tmp = arr[lo]; arr[lo] = arr[hi]; arr[hi] = tmp; }
Common Array Patterns
// Initialize all to same value for (int i = 0; i < n; i++) arr[i] = val; // Find max int max = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > max) max = arr[i]; // Linear search int idx = -1; for (int i = 0; i < n; i++) if (arr[i] == target) { idx = i; break; } // Tokenize a string char line[] = "one two three"; char *tok = strtok(line, " "); while (tok) { printf("%s\n", tok); tok = strtok(NULL, " "); // NULL continues from last position }