Coding Techniques
Pointers · Study material
Two-pointer technique
Keep one pointer at the start and one at the end, and move them towards each other. It solves reversing, palindrome checks and pair-sum problems in a single pass without extra memory.
#include <stdio.h>
#include <string.h>
int is_palindrome(const char *s) {
const char *l = s, *r = s + strlen(s) - 1;
while (l < r) {
if (*l != *r)
return 0;
l++;
r--;
}
return 1;
}
int main(void) {
printf("level -> %d\n", is_palindrome("level"));
printf("pointer -> %d\n", is_palindrome("pointer"));
return 0;
}
level -> 1 pointer -> 0
The loop stops when the pointers meet, so each character is compared once – O(n) time and O(1) extra space.
Returning several values with output parameters
A C function returns only one value. To give back more, the caller passes addresses and the function writes the results through them. Mark input pointers const so readers (and the compiler) know they are not changed.
#include <stdio.h>
void min_max(const int *a, int n, int *min, int *max) {
*min = *max = a[0];
for (const int *p = a + 1; p < a + n; p++) {
if (*p < *min) *min = *p;
if (*p > *max) *max = *p;
}
}
int main(void) {
int marks[] = {72, 91, 58, 84, 66};
int lo, hi;
min_max(marks, 5, &lo, &hi);
printf("min = %d, max = %d\n", lo, hi);
return 0;
}
min = 58, max = 91
Walking an array or string with a pointer
Instead of an index, move a pointer through the data. The loop ends at the terminating '\0' for strings, or at a + n for arrays.
#include <stdio.h>
int count_char(const char *s, char c) {
int n = 0;
for (; *s != '\0'; s++) /* move the pointer itself, no index needed */
if (*s == c)
n++;
return n;
}
int main(void) {
printf("'m' appears %d times in programming\n", count_char("programming", 'm'));
return 0;
}
'm' appears 2 times in programming
Changing the parameter s inside the function is safe: it is the function's own copy of the address.
Reading complex declarations (right-left rule)
Start at the name, read right while you can, then left, and step out of each pair of brackets.
| Declaration | Meaning |
|---|---|
int *a[5] | array of 5 pointers to int |
int (*a)[5] | pointer to an array of 5 ints |
int *f(void) | function returning a pointer to int |
int (*f)(int) | pointer to a function taking int and returning int |
char **argv | pointer to a pointer to char |
int (*ops[3])(int, int) | array of 3 pointers to functions (int, int) → int |
Safe pointer habits
- Initialise every pointer: a real address or
NULL. - Check the result of
malloc(),calloc()andrealloc()for NULL. - Write
p = malloc(n * sizeof *p)so the size always matches the pointer type. - After
free(p), setp = NULLto avoid a dangling pointer. - Use
constfor pointers you only read through. - Compile with
-Wall -Wextra -fsanitize=addresswhile learning – it catches most pointer bugs at once.