C Cheat Sheet
Program skeleton
// Basic program
#include <stdio.h>
int main(void) { printf("Hi\n"); return 0; }
// Compile and run
// gcc main.c -o main -Wall && ./main
Input and output
scanf("%d", &n);
scanf("%d %lld %lf %c %s", &a, &b, &d, &c, str);
printf("%d %lld %.2f %c %s\n", a, b, d, c, str);
fgets(line, sizeof line, stdin);
Types and limits
char c = 'A'; int i = 1; long long ll = 1LL << 40;
float f = 1.5f; double d = 2.5; unsigned u = 4u;
#include <limits.h>
INT_MAX; INT_MIN; LLONG_MAX;
sizeof(int); (double)a / b;
Control flow
if (a > b) { } else if (a == b) { } else { }
switch (x) { case 1: break; default: break; }
for (int i = 0; i < n; i++) { }
while (cond) { }
do { } while (cond);
Arrays and strings
int a[5] = {0};
int n = sizeof(a) / sizeof(a[0]);
int m[3][3];
#include <string.h>
strlen(s); strcpy(d, s); strcat(d, s); strcmp(a, b);
strchr(s, 'x'); strstr(s, "ab");
Pointers and memory
int *p = &x; *p = 5;
int *a = malloc(n * sizeof(int));
int *z = calloc(n, sizeof(int));
a = realloc(a, 2 * n * sizeof(int));
free(a); a = NULL;
Structs and functions
typedef struct { int x, y; } Point;
Point pt = {1, 2}; Point *pp = &pt; pp->x = 5;
void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }
Files
FILE *f = fopen("a.txt", "r");
fprintf(f, "%d\n", x); fscanf(f, "%d", &x);
fclose(f);
Full C documentation