Pointers
A pointer stores a memory address. Instead of containing a value directly, it names a place where a value can be read or written.
In C, a pointer type is written as T*, meaning “pointer to T”:
int value = 42;
int* ptr = &value;&value takes the address of value. *ptr dereferences the pointer and accesses the value stored at that address.
printf("%d\n", *ptr); // 42Pointers are useful for sharing data without copying it, building linked data structures, passing large values to functions, and working with heap allocations.
Null Pointers
A null pointer points to no valid object.
int* ptr = NULL;Dereferencing a null pointer is invalid. Code that accepts a pointer should either document that it cannot be null or check before dereferencing it.
Pointer Arithmetic
Pointer arithmetic moves by elements, not bytes.
int values[] = {10, 20, 30};
int* ptr = values;
printf("%d\n", *(ptr + 1)); // 20For an int*, ptr + 1 advances by sizeof(int) bytes.
Common Bugs
- Dangling pointer: points to memory that has already been freed or gone out of scope.
- Null dereference: dereferences
NULL. - Double free: frees the same allocation more than once.
- Memory leak: loses the last pointer to an allocation without freeing it.
- Out-of-bounds pointer: points outside the valid object or array.