Pointer Arithmetic with Arrays
In C, array names decay into pointers. Adding an integer to a pointer (pointer arithmetic) moves the pointer by that many elements, not bytes.
int arr[] = {10, 20, 30};int *ptr = arr;int val = *(ptr + 2);
Hand-picked snippets across TypeScript, Python, Rust, Go, and more — each one comes with a line-by-line breakdown so you can read it like the people who wrote it.
In C, array names decay into pointers. Adding an integer to a pointer (pointer arithmetic) moves the pointer by that many elements, not bytes.
int arr[] = {10, 20, 30};int *ptr = arr;int val = *(ptr + 2);
Using malloc to allocate memory for structures on the heap is essential when the size or lifetime of the data isn't known at compile time.
typedef struct { int id; char *name; } User;User *u = (User *)malloc(sizeof(User));if (u != NULL) {u->id = 1;free(u);}
Bitwise operators are used to store multiple boolean flags within a single integer, which is highly memory-efficient and fast.
#define READ (1 << 0)#define WRITE (1 << 1)unsigned char permissions = 0;permissions |= READ;if (permissions & READ) {/* logic */}
A static local variable retains its value between function calls, initialized only once when the program starts.
void track_calls() {static int count = 0;count++;printf("Called %d times\n", count);}
The 'restrict' qualifier is a hint to the compiler that for the lifetime of the pointer, only the pointer itself or a value derived from it will be used to access the object it points to. This allows the compiler to perform optimizations like vectorization that would otherwise be unsafe due to potential pointer aliasing.
void add_arrays(int *restrict a, int *restrict b, int *restrict result, int n) {for (int i = 0; i < n; i++) {result[i] = a[i] + b[i];}}
Variadic functions allow you to pass a variable number of arguments to a function. This is achieved using the macros defined in <stdarg.h>. You must provide at least one fixed argument (like 'count') to know where the variable list starts.
#include <stdarg.h>void print_log(int count, ...) {va_list args;va_start(args, count);for (int i = 0; i < count; i++) {printf("%s ", va_arg(args, char*));}va_end(args);}
A union allows different data types to be stored in the same memory location. The size of the union is determined by its largest member. This is particularly useful in systems programming for overlaying data structures or accessing specific parts of a memory word.
union HardwareRegister {uint32_t full_word;struct {uint16_t lower_half;uint16_t upper_half;} parts;};
Wrapping a multi-statement macro in a 'do { ... } while (0)' block ensures it behaves as a single statement. This prevents logical errors when the macro is used inside 'if' statements without curly braces and forces the user to provide a semicolon.
#define SAFE_FREE(ptr) do { \free(ptr); \ptr = NULL; \} while (0)