BASIC STRUCTURE
Section titled “BASIC STRUCTURE”#include <stdio.h>int main() { // code return 0;}Data Types
Section titled “Data Types”| Type | Size | Format | Range |
|---|---|---|---|
char | 1 byte | %c | -128 to 127 |
int | 4 bytes | %d | -2,147,483,648 to 2,147,483,647 |
float | 4 bytes | %f | 3.4E-38 to 3.4E+38 |
double | 8 bytes | %lf | 1.7E-308 to 1.7E+308 |
short | 2 bytes | %hd | -32,768 to 32,767 |
long | 8 bytes | %ld | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
Input and Output
Section titled “Input and Output”/* --- INPUT/OUTPUT CHEAT SHEET --- */
// Standard Console I/Oprintf("Value: %d\n", num); // Output formatted datascanf("%d", &num); // Input formatted data (use & for address)getchar(); // Read a single character from stdinputchar('A'); // Write a single character to stdoutputs("Hello"); // Print string + automatic newlinefgets(str, 100, stdin); // Read string safely (prevents overflow)
// String Buffer I/O (In-memory)sprintf(buffer, "Age: %d", age); // Write formatted data TO a stringsscanf(buffer, "%d", &age); // Read formatted data FROM a string
// File Stream I/OFILE *fp = fopen("data.txt", "r"); // Open for reading ("r"), writing ("w"), or appending ("a")fprintf(fp, "ID: %d", id); // Print formatted data to filefscanf(fp, "%d", &id); // Read formatted data from filefputs("No newline", fp); // Write string to file without adding \nfgetc(fp); // Read single character from filefclose(fp); // Always close your file pointers!
// Essential Format Specifiers// %d (int), %u (unsigned), %f (float), %lf (double), %c (char), %s (string), %p (pointer)
// Buffer Clearing Trick (Fixes skipped scanf/fgets issues)while ((getchar()) != '\n' && getchar() != EOF);FORMAT SPECIFIERS
Section titled “FORMAT SPECIFIERS”| Specifier | Type |
|---|---|
%d, %i | Integer |
%f | Float |
%lf | Double |
%c | Character |
%s | String |
%p | Pointer |
%x | Hexadecimal |
%o | Octal |
%% | Print % |
Operators
Section titled “Operators”// ARITHMETIC+ - * / % ++ --
// RELATIONAL== != > < >= <=
// LOGICAL&& || !
// BITWISE& | ^ ~ << >>
// ASSIGNMENT= += -= *= /= %= &= |= ^= <<= >>=
// TERNARYcondition ? true : falseControl flow
Section titled “Control flow”// IF-ELSEif (x > 0) { }else if (x == 0) { }else { }
// SWITCHswitch(x) { case 1: break; case 2: break; default: break;}
// FOR LOOPfor (int i = 0; i < 10; i++) { }
// WHILE LOOPwhile (condition) { }
// DO-WHILEdo { } while (condition);
// BREAK, CONTINUEbreak; // Exit loopcontinue; // Skip iterationFunctions
Section titled “Functions”// DECLARATIONreturn_type func_name(type param);
// DEFINITIONint add(int a, int b) { return a + b;}
// CALLresult = add(5, 3);Arrays
Section titled “Arrays”int arr[5]; // Declarationint arr[] = {1,2,3,4,5}; // Initializationarr[0] = 10; // Accessint len = sizeof(arr)/sizeof(arr[0]); // Length
// 2D ARRAYint matrix[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};Strings
Section titled “Strings”/* --- STRING MANIPULATION (<string.h>) --- */
char str[100] = "Hello";strlen(str); // Returns length (excluding null terminator '\0')strcpy(dest, src); // Copy src to dest (risky if dest is small)strncpy(dest, src, n); // Copy up to n characters (safer)strcat(dest, src); // Append src to end of deststrncat(dest, src, n); // Append up to n characters (safer)strcmp(s1, s2); // Compare: 0 if equal, <0 if s1 < s2, >0 if s1 > s2strncmp(s1, s2, n); // Compare first n charactersstrcasecmp(s1, s2); // Case-insensitive compare (POSIX/Strings.h)
// Searching & Tokenizingstrchr(str, 'c'); // Pointer to first occurrence of 'c' (NULL if not found)strrchr(str, 'c'); // Pointer to LAST occurrence of 'c'strstr(str, "sub"); // Pointer to first occurrence of substring "sub"strspn(str, "abc"); // Length of initial segment containing only 'a', 'b', or 'c'strcspn(str, "123"); // Length of initial segment NOT containing '1', '2', or '3'strtok(str, ","); // Tokenize string by delimiter (updates state with NULL)
// Character Logic (<ctype.h>) - Useful for loopsisalpha(c); // Non-zero if alphabeticisdigit(c); // Non-zero if 0-9isspace(c); // Non-zero if whitespace (space, tab, \n)toupper(c); // Convert to uppercasetolower(c); // Convert to lowercase
// Memory Operations (also in <string.h>)memset(str, 0, sizeof(str)); // Fill memory with a constant (e.g., zeroing an array)memcpy(dest, src, n); // Copy raw memory blocks (faster than strcpy)memcmp(s1, s2, n); // Compare raw memory blocksPointers
Section titled “Pointers”/* --- POINTERS & MEMORY (<stdlib.h>) --- */
int *ptr; // Pointer to an integerptr = &var; // Store address of var in ptr*ptr = 10; // Dereference: change value at address to 10int **dptr = &ptr; // Pointer to a pointer (Double Pointer)
// Array & Pointer Equivalencearr[i] == *(arr + i); // Standard indexing vs pointer arithmetic*(ptr + 1); // Moves to the next memory block (size of int)
// Dynamic Memory Allocation (The Heap)ptr = (int*)malloc(n * sizeof(int)); // Allocate memory for n integersptr = (int*)calloc(n, sizeof(int)); // Allocate AND zero-initialize memoryptr = realloc(ptr, new_size); // Resize previously allocated blockfree(ptr); // Deallocate memory (prevent leaks!)ptr = NULL; // Best practice: nullify after freeing
// Constants and Pointersconst int *p = &x; // Data is constant (cannot change *p)int * const p = &x; // Pointer is constant (cannot change p)
// Special Pointersvoid *vptr; // Generic pointer (can point to any type)int (*f)(int); // Function pointer (points to a function)if (ptr == NULL) // Null check: always verify before dereferencingMemory Management
Section titled “Memory Management”/* --- DYNAMIC MEMORY MANAGEMENT (<stdlib.h>) --- */
// Allocation Functionsvoid *ptr = malloc(size); // Allocate 'size' bytes (contains garbage values)void *ptr = calloc(n, size); // Allocate n * size bytes (all bits set to 0)void *ptr = realloc(old_ptr, s); // Resize block; may move to a new addressfree(ptr); // Release memory back to the system
// Safety & Best Practicesif (ptr == NULL) { // ALWAYS check if allocation failed perror("malloc failed"); exit(1);}
// Avoiding Memory Leaks & Errorsfree(ptr); // 1. Deallocate when finishedptr = NULL; // 2. Prevent "Dangling Pointer" (pointing to freed memory)
// Memory Operations (<string.h>)memset(ptr, 0, n * sizeof(int)); // Manually zero out a blockmemcpy(dest, src, n); // Copy n bytes from src to destmemmove(dest, src, n); // Safer copy if memory regions overlap
// Common Pitfalls// 1. Memory Leak: Forgetting to free() before losing the pointer.// 2. Double Free: Calling free() on the same pointer twice (causes crashes).// 3. Buffer Overflow: Writing past the allocated size of the block.Structures
Section titled “Structures”// DEFINITIONstruct Person { char name[50]; int age;};
// DECLARATIONstruct Person p1;p1.age = 25;
// WITH TYPEDEFtypedef struct { int x, y;} Point;
union Data { int i; float f; char str[20]; // Only ONE member can be held at a time};// sizeof(union Data) is the size of its largest member (20 bytes)
Point p2 = { .y = 50, .x = 10 }; // Initialize by name, any orderFile I/O
Section titled “File I/O”FILE *fp;
// OPEN MODES: "r" "w" "a" "r+" "w+" "a+"fp = fopen("file.txt", "r");
// READ/WRITEfprintf(fp, "%d", num); // Writefscanf(fp, "%d", &num); // Readfgetc(fp); // Read charfputc('A', fp); // Write charfgets(str, 100, fp); // Read linefputs("text", fp); // Write string
fclose(fp); // Close file
/* --- ADVANCED FILE I/O --- */
// 1. ERROR CHECKINGif ((fp = fopen("file.txt", "r")) == NULL) { perror("Error opening file"); // Prints system error message}
// 2. BINARY READ/WRITE// fwrite(data_ptr, size_of_element, count, fp);fwrite(&struct_var, sizeof(struct_var), 1, fp);fread(&struct_var, sizeof(struct_var), 1, fp);
// 3. FILE POSITIONING (SEEKING)fseek(fp, 0, SEEK_END); // Move to end of filelong size = ftell(fp); // Get current position (useful for file size)rewind(fp); // Move cursor back to start (offset 0)// Origin options: SEEK_SET (start), SEEK_CUR (current), SEEK_END (end)
// 4. BUFFERING & STATUSfflush(fp); // Force write buffered data to diskfeof(fp); // Returns non-zero if End-Of-File reachedferror(fp); // Returns non-zero if error occurredclearerr(fp); // Resets error and EOF indicators
// 5. FILE SYSTEM OPSremove("old_file.txt"); // Delete a filerename("old.txt", "new.txt"); // Rename a filePreprocessor Directive
Section titled “Preprocessor Directive”#include <stdio.h> // Search system directories#include "my_file.h" // Search local directory first
#define PI 3.14159 // Constant macro#define SQUARE(x) ((x) * (x)) // Function-like macro (use parentheses!)#define MAX(a,b) ((a)>(b)?(a):(b))
// 1. CONDITIONAL COMPILATION#if defined(WIN32) || defined(_WIN64) #define PLATFORM "Windows"#elif defined(__linux__) #define PLATFORM "Linux"#else #define PLATFORM "Unknown"#endif
// 2. HEADER GUARDS (Prevents double inclusion)#ifndef MY_HEADER_H#define MY_HEADER_H // Header content here#endif
// 3. PREDEFINED MACROS (Useful for debugging)__FILE__ // Current file name (string)__LINE__ // Current line number (int)__DATE__ // Compilation date (string)__TIME__ // Compilation time (string)__func__ // Current function name (string, C99)
// 4. STRINGIFICATION & CONCATENATION#define TO_STR(x) #x // Converts x to "x"#define CONCAT(a, b) a##b // Joins a and b into one token
// 5. ERROR & PRAGMA#error "ErrorMessage" // Stops compilation with a message#pragma once // Modern alternative to header guards#undef PI // Removes macro definitionMath Functions (#include <math.h>)
Section titled “Math Functions (#include <math.h>)”pow(x, y) // x^ysqrt(x) // Square rootabs(x) // Absolute valueceil(x) // Round upfloor(x) // Round downsin(x) cos(x) tan(x)log(x) log10(x)Common Header Files
Section titled “Common Header Files”<stdio.h> // I/O functions<stdlib.h> // Memory, conversion, random<string.h> // String operations<math.h> // Math functions<ctype.h> // Character functions<time.h> // Time/date functions<stdbool.h> // Boolean type<limits.h> // Type limits (INT_MAX, etc.)TYPEDEF & ENUM
Section titled “TYPEDEF & ENUM”// TYPEDEFtypedef unsigned long ulong;typedef int* intptr;
// ENUMenum Day {SUN, MON, TUE, WED, THU, FRI, SAT};enum Day today = MON;USEFUL SNIPPETS
Section titled “USEFUL SNIPPETS”// SWAP TWO NUMBERStemp = a; a = b; b = temp;
// TERNARY OPERATORmax = (a > b) ? a : b;
// SIZEOF OPERATORsize = sizeof(int); // Returns 4
// COMMAND LINE ARGUMENTSint main(int argc, char *argv[]) { }COMPILATION & EXECUTION
gcc program.c -o program # Compile./program # Rungcc -Wall -g program.c # Debug mode