- How to walk an array using a single pointer instead of an integer index
- Why
ptr < arr + nis the pointer equivalent ofi < n - How to recover the index from a pointer using pointer subtraction
- Why pointer-based search is still O(n) and how it compares to array indexing
- How the same function can search arrays of different lengths
How Pointer-Based Linear Search Works
Linear search is the simplest search algorithm: look at every element in turn, from first to last, until you find the one you want or run out of elements. When you write it with an array index, you have a loop like for (i = 0; i < n; i++) if (a[i] == key) .... When you write it with a pointer, the same idea is expressed by moving a pointer from element to element. The pointer walks the array, and at each step you check *ptr instead of a[i].
The pointer version isn't faster in big-O terms — it's still O(n) comparisons in the worst case, because every element may need to be checked. But it is arguably cleaner: there is no index variable, no a[i] indexing operation, and no need to pass the length separately if you use a sentinel or an end pointer. The pointer is the position. This is the same idea that powers std::find in C++ and many C library search routines.
The loop condition is the crucial part. With an index you write i < n. With a pointer you write ptr < arr + n. Both mean the same thing: "while there is still an element to look at." When ptr == arr + n, the pointer has stepped past the last element and the loop stops. This is safe: forming the one-past-the-end pointer is legal in C (it's used for loop bounds), as long as you don't dereference it.
💡 In one line: Start a pointer at the array's first element, compare *ptr with the key, advance ptr, and stop when ptr reaches arr + n.
The Three Steps of the Search
| Step | Pointer operation | Effect |
|---|---|---|
| 1. Set the pointer to the start | int *ptr = arr; | ptr points at the first element |
| 2. Compare and advance | while (ptr < arr + n) { if (*ptr == key) found; ptr++; } | Each element is examined exactly once, in order |
| 3. Report result | ptr - arr or -1 | Index of the match, or a not-found signal |
Why use a pointer at all when an index works fine? There are a few good reasons. First, if the array is passed to a function, the function receives a pointer anyway (arrays decay to pointers in function arguments), so working with a pointer is natural. Second, the pointer version makes the "range" of the search explicit: the array is the half-open range [arr, arr + n), and the loop visits exactly that range. Third, once you're comfortable with this pattern, you can reuse it for any container that exposes pointers — including dynamically allocated buffers, which have no built-in length.
One subtle but important point: pointer arithmetic respects the type. If arr is an int array, then arr + 1 advances by sizeof(int) bytes, not one byte. This is why the loop works for arrays of any element type — the compiler takes care of the scaling. If you were to walk the same memory with a char *, you would have to multiply by sizeof(int) yourself. The typed pointer saves you from that.
Complete C Program
Program: linear search in an array using pointers
#include <stdio.h>
#define MAX 100
/* Linear search using pointers.
Returns the index of key, or -1 if not found. */
int linear_search(const int *arr, int n, int key) {
const int *ptr = arr; /* start at the first element */
const int *end = arr + n; /* one past the last element */
while (ptr < end) {
if (*ptr == key) {
return (int)(ptr - arr); /* pointer subtraction gives the index */
}
ptr++; /* move to the next element */
}
return -1; /* not found */
}
int main(void) {
int arr[MAX];
int n, key, i, result;
printf("How many elements? ");
if (scanf("%d", &n) != 1 || n <= 0 || n > MAX) {
printf("Invalid size.\n");
return 1;
}
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++) {
if (scanf("%d", &arr[i]) != 1) {
printf("Invalid input.\n");
return 1;
}
}
printf("Enter the key to search: ");
if (scanf("%d", &key) != 1) {
printf("Invalid key.\n");
return 1;
}
result = linear_search(arr, n, key);
if (result == -1) {
printf("\n%d was not found in the array.\n", key);
} else {
printf("\n%d was found at index %d (position %d).\n",
key, result, result + 1);
}
return 0;
}
Program Output
How many elements? 5
Enter 5 integers:
10 20 30 40 50
Enter the key to search: 30
30 was found at index 2 (position 3).
A second run, with a key that isn't present:
How many elements? 5
Enter 5 integers:
10 20 30 40 50
Enter the key to search: 35
35 was not found in the array.
In the first run, the pointer walks from index 0 to index 2, where *ptr == 30, and returns 2. In the second run, the pointer visits every index from 0 to 4 without a match, reaches arr + 5 (the end pointer), and the function returns -1. Both outcomes are handled by the same loop — no special-casing is needed for the "found at the beginning" or "found at the end" cases.
Step-by-Step Explanation
Let's walk through the pointer mechanics in detail.
1. The function signature
linear_search(const int *arr, int n, int key) receives a pointer to the array's first element, the number of elements, and the key to find. The const on arr is a promise that the function will not modify the array — it only reads. This is good practice: the search is a read-only operation, so the pointer should be const. The caller doesn't have to pass a non-const array, and the compiler will catch any accidental write inside the function.
2. Setting up the pointers
const int *ptr = arr; — ptr starts at the first element. const int *end = arr + n; — end is one past the last element. Both are const int *, matching the parameter. The variable name end is conventional for the one-past-the-end pointer; it's not dereferenceable, but comparing against it is exactly what we need.
3. The loop condition
while (ptr < end) is the pointer form of i < n. When ptr reaches arr + n, the loop stops. This is a half-open range: it includes arr + 0 through arr + n - 1, which are exactly the n valid elements. The one-past-the-end pointer is never dereferenced, only compared. This idiom appears everywhere in C — memcpy, qsort, and the standard library's iterator equivalents all use it.
4. The comparison
if (*ptr == key) dereferences the pointer and compares the element to the key. If they're equal, we've found the element. The function then returns (int)(ptr - arr). Pointer subtraction between two pointers into the same array gives the number of elements between them — since arr points at index 0, ptr - arr is exactly the index of the matching element. For example, if ptr points at the third element, ptr - arr is 2.
5. Advancing the pointer
ptr++ moves the pointer to the next element. Because ptr is a typed pointer (const int *), the increment advances by sizeof(int) bytes, not by one byte. The compiler handles the scaling automatically. This is why the same code works for int, float, double, or any other element type — you just change the pointer's type.
6. Returning not found
If the loop terminates because ptr == end, the key isn't in the array. The function returns -1, a conventional "not found" indicator. The caller checks for -1 and prints the appropriate message. This is the same convention used by strchr (returns NULL) and many search routines (return a sentinel), but -1 is simpler for index-returning functions because valid indices are always non-negative.
7. Example trace
For the array [10, 20, 30, 40, 50] with key = 30:
- Iteration 1:
ptrpoints at index 0,*ptr == 10. 10 ≠ 30, so advance.ptrnow points at index 1. - Iteration 2:
*ptr == 20. 20 ≠ 30, so advance.ptrnow points at index 2. - Iteration 3:
*ptr == 30. 30 == 30, so returnptr - arr = 2. The function returns 2 immediately — the remaining elements (40, 50) are never examined.
8. The worst case
For a key that isn't in the array, or one that's at the very end, the loop runs n times. Each iteration does one comparison and one pointer increment — both O(1). So the total time is O(n). No sorting or indexing structure is needed, which is the main advantage of linear search: it works on unsorted data and requires no preprocessing. The cost is that it can't do better than O(n) in the worst case, unlike binary search's O(log n) on sorted data.
9. Why const on the pointer parameter
The const int *arr parameter means "the function promises not to modify the integers that arr points at." Without it, callers passing a const array would get a compiler warning or error. With it, the function can still reassign its local ptr (the pointer variable itself isn't const), but it can't write through any pointer derived from arr. This is a safety and documentation feature — both the compiler and the reader know the array is read-only.
10. Pointer version vs index version
Here's the same function written with an index:
int linear_search_index(const int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) return i;
}
return -1;
}
Both versions are correct and O(n). The pointer version has no separate index variable, which some programmers find cleaner; the index version is arguably more readable for beginners. In practice, the compiler often generates identical machine code for both, because arr[i] is defined as *(arr + i) anyway. The choice is a matter of style and of what the surrounding code looks like.
11. Searching a sub-range
Because the function works on pointers, it can easily search a sub-range: pass arr + start and a length of end - start. The returned index is relative to the start of the range, not the original array — you'd add start to get the absolute index. This flexibility is one reason pointer-based interfaces are common in C libraries: the same function handles full-array and slice searches without extra code.
12. Complexity summary
Time: O(n) in the worst case (key not present or at the end), O(1) in the best case (key at the first position). Space: O(1) — just a few pointer variables. The function is stable (returns the first matching index), works on unsorted data, and requires no extra memory. Linear search is the right choice when the array is small, unsorted, or searched only a few times; sorting plus binary search pays off only when there are many searches.
🎯 Remember this: The pointer walks the array from arr to arr + n. The index of a match is recovered with ptr - arr. The loop condition ptr < arr + n is the pointer form of i < n, and the one-past-the-end pointer is legal to form but never to dereference.
Frequently Asked Questions
1. Why use pointers for linear search instead of an index?
There's no performance advantage — both are O(n) and the compiler typically generates the same code. The pointer version is natural because arrays decay to pointers when passed to functions, and because it makes the half-open range [arr, arr + n) explicit. It's also the form that generalises to other containers and to dynamically allocated buffers. For simple beginner programs, the index version is arguably more readable; the pointer version is more idiomatic in library code.
2. What does ptr - arr return, and why is it an index?
Pointer subtraction between two pointers into the same array returns the number of elements between them. Since arr points at index 0 and ptr points at the matching element, ptr - arr is exactly the index of the match. The result is of type ptrdiff_t (usually a signed integer); the cast to int is safe for arrays smaller than INT_MAX elements. If the two pointers aren't into the same array, the subtraction is undefined — but in this loop they always are.
3. Is arr + n safe when it's one past the end?
Yes. Forming a pointer one past the end of an array is explicitly allowed in C, as long as you don't dereference it. This is the standard idiom for range loops: for (p = arr; p < arr + n; p++). Dereferencing arr + n would be undefined, but comparing against it and stepping to it are fine. The same applies to ptr++ that moves ptr from arr + n - 1 to arr + n: legal, because it's the last valid "one past" position.
4. What if the array contains duplicate values?
The function returns the index of the first match, because it returns as soon as it finds an equal element. If you want the last occurrence, walk the array from the end backward, or continue the search after a match and remember the last index. Neither version is more "correct" — it depends on what the caller needs. Many search functions document which occurrence they return so the caller isn't surprised.
5. Can this search a sorted array too?
Yes — linear search works on any array, sorted or not. But if the array is sorted, binary search is far more efficient: O(log n) instead of O(n). Use linear search when the array is small, unsorted, or searched only rarely. The sorting cost (O(n log n)) plus binary search only pays off after enough searches; for a single search, linear is usually the right choice even on sorted data.
6. What is the time complexity of this implementation?
Worst case is O(n): the key isn't present, or it's at the very end, so every element is examined. Best case is O(1): the key is at index 0 and is found on the first comparison. On average, assuming the key is equally likely to be anywhere (or absent), it's O(n). Space is O(1) — only a few pointer variables and the loop's bookkeeping. This is optimal for an unordered search: no comparison-based algorithm can find an element in an unsorted array faster than O(n) in the worst case.
💡 Tip: Once this works, try modifying it to find the last occurrence instead of the first, or to count how many times the key appears. Both are small changes to the same pointer walk — and both reinforce the idea that the pointer is just a position you can move and compare.