Master C pointers from memory addresses to pointer arithmetic, dereferencing, dynamic memory allocation with malloc and free, and function pointers.
What is a Pointer in C?
A pointer is a variable that stores the memory address of another variable. Pointers are the defining feature of C, providing low-level hardware memory access, efficient pass-by-reference semantics, and dynamic heap allocation.
Address-of (&) and Dereference (*) Operators
&variable: Returns the hexadecimal memory address where the variable is located in RAM.*pointer: Dereferences the pointer, accessing or mutating the value stored at that address.
c (ISO Standard)#include <stdio.h> int main() { int value = 42; int *ptr = &value; /* ptr holds the memory address of value */ printf("Value: %d\n", value); printf("Memory Address of value (&value): %p\n", (void*)&value); printf("Pointer Address (ptr): %p\n", (void*)ptr); printf("Dereferenced Pointer (*ptr): %d\n", *ptr); /* Modifying value via pointer dereference */ *ptr = 99; printf("Updated value after *ptr = 99: %d\n", value); return 0; }
Pointer Arithmetic
When you add or subtract integers from a pointer, C scales the operation by the byte size of the pointed-to data type (sizeof(*ptr)):
c (ISO Standard)#include <stdio.h> int main() { int arr[3] = {100, 200, 300}; int *ptr = arr; /* points to arr[0] */ printf("First element via pointer: %d\n", *ptr); printf("Second element via *(ptr + 1): %d\n", *(ptr + 1)); printf("Third element via *(ptr + 2): %d\n", *(ptr + 2)); return 0; }
Dynamic Memory Allocation (malloc and free)
Heap memory is allocated manually at runtime using <stdlib.h>:
c (ISO Standard)#include <stdio.h> #include <stdlib.h> int main() { int n = 5; int *dynamicArray = (int *)malloc(n * sizeof(int)); if (dynamicArray == NULL) { printf("Memory allocation failed!\n"); return 1; } for (int i = 0; i < n; i++) { dynamicArray[i] = (i + 1) * 10; printf("dynamicArray[%d] = %d\n", i, dynamicArray[i]); } /* Always release dynamically allocated heap memory */ free(dynamicArray); dynamicArray = NULL; return 0; }
Related C Tutorials & Practical Examples
- Connect arrays and pointer decay in Arrays in C Programming.
- Practice pointer passing with our Swap Two Numbers in C Example.
- Step through pointer addresses visually in our Online C Debugger.