Pointers are variables that store the address of another variable. They provide direct access to memory and are powerful for dynamic memory management, arrays, and functions.
1. The Address (&) and Indirection (*) Operators
- Address-of (&) → Gives the memory address of a variable.
int x = 10;
printf(“%p”, &x); // Prints address of x
- Indirection / Dereference (*) → Accesses the value at an address.
int *p = &x;
printf(“%d”, *p); // Prints 10
2. Declaration & Initialization
int *p; // Declares pointer to int
int x = 5;
p = &x; // Initializes pointer with address of x
3. Pointer to Pointer
- A pointer that stores the address of another pointer.
int x = 10;
int *p = &x;
int **pp = &p;
printf(“%d”, **pp); // Prints 10
4. Pointer Expressions
- Pointers can be compared (==, !=) and incremented/decremented.
- Useful in arrays and dynamic memory operations.
5. Pointer Arithmetic
- Operations: +, -, ++, —
- Moves pointer by the size of the data type it points to.
int arr[3] = {10, 20, 30};
int *p = arr;
p++; // Points to arr[1]
6. Passing Pointer to a Function
- Allows modification of original variables.
void increment(int *x) { (*x)++; }
int a = 5;
increment(&a); // a becomes 6
7. Pointer and Array
- Array name acts as a pointer to the first element.
int arr[3] = {1,2,3};
int *p = arr;
printf(“%d”, *(p+1)); // Prints 2
8. Array of Pointers
- Stores addresses of multiple variables.
int a=1, b=2, c=3;
int *ptr[3] = {&a, &b, &c};
9. Pointer and String
- Strings are arrays of characters; can be manipulated via pointers.
char str[] = “Hello”;
char *p = str;
printf(“%c”, *(p+1)); // Prints ‘e’
10. Dynamic Memory Allocation
- Allocates memory at runtime using malloc(), calloc(), realloc(), free().
int *ptr = (int*)malloc(5 * sizeof(int)); // Allocate 5 integers
free(ptr); // Free memory
Key Takeaways
- Pointers store addresses and allow direct memory access.
- & gives address; * accesses value at address.
- Pointers can point to pointers, arrays, and strings.
- Pointer arithmetic helps traverse arrays efficiently.
- Passing pointers to functions allows modification of original variables.
- Dynamic memory allocation manages memory at runtime.
- Array of pointers and pointer to string are useful in advanced C programming.