Module 10: Pointers & Deep Memory Mastery
Duration: 5.0 Hours • The Soul of CPointer Arithmetic & Byte Scaling
Why ptr + 1 advances by sizeof(*ptr) bytes
When you add 1 to a pointer, the CPU advances the address by the size of the underlying data type:
pointer_arithmetic.c
int numbers[3] = {100, 200, 300}; int *ptr = numbers; // Address: 0x1000 // ptr + 1 advances by 4 bytes (sizeof(int)) -> Address: 0x1004! printf("Value: %d\\n", *(ptr + 1)); // Prints 200 double d_arr[2] = {1.1, 2.2}; double *d_ptr = d_arr; // Address: 0x2000 // d_ptr + 1 advances by 8 bytes (sizeof(double)) -> Address: 0x2008!
Double Pointers (int **ptr) & Modifying Pointers in Functions
Pointer to a Pointer architecture
If you want a function to modify where a pointer points (e.g. allocating memory inside a helper function or linked list head insertion), you must pass a pointer to that pointer:
double_pointer.c
void allocate_buffer(int **ptr_address, size_t size) { *ptr_address = malloc(size * sizeof(int)); } int main(void) { int *my_array = NULL; allocate_buffer(&my_array, 100); // my_array now successfully points to the 100-integer heap block! free(my_array); return 0; }
Function Pointers & Dynamic Dispatch Tables
Passing behavior dynamically in C
function_pointer.c
// Typedef signature: int (*Operation)(int, int) typedef int (*BinOp)(int, int); int add(int a, int b) { return a + b; } int sub(int a, int b) { return a - b; } void execute(int x, int y, BinOp op) { printf("Result: %d\\n", op(x, y)); }
1. Pointer Types Summary
| Pointer Concept | Syntax | Meaning |
|---|---|---|
| Null Pointer | NULL | Points nowhere (0x0). Safe check before dereferencing. |
| Wild Pointer | int *p; | Uninitialized pointer holding random garbage memory address. |
| Dangling Pointer | free(p); | Points to memory that has already been deallocated. |
| Generic Pointer | void *p; | Holds raw address of any type; must be cast before dereference. |
2. Practice Exercises & Solutions
Exercise 10.1: What is the difference between
const int *p; and int * const p;?
View Solution
-
-
const int *p;: Pointer to CONSTANT integer. You cannot change the value (*p = 10; // ERROR), but you can point p elsewhere.-
int * const p;: CONSTANT pointer to an integer. You can change the integer value, but the pointer address is locked.