C array search with explicit length
Search only within the supplied array bounds.
C
#include <stdio.h>
#include <assert.h>
int find(const int values[], int n, int target) {
for (int i = 0; i < n; i++) {
if (values[i] == target) return i;
}
return -1;
}
int main(void) {
int values[] = {5, 2, 7};
printf("%d\n", find(values, 3, 7));
assert(find(values, 0, 7) == -1);
assert(find(values, 3, 9) == -1);
return 0;
}Output
2
Explanation
An array parameter is adjusted to a pointer in a C function. The function does not automatically know how many elements are available, so length must be passed separately.
This search returns the first matching index or -1. The caller promises that n is nonnegative and no larger than the accessible element count.
Explore the dry run
Guided walkthroughReady
1
#include <stdio.h>2
#include <assert.h>3
int find(const int values[], int n, int target) {4
for (int i = 0; i < n; i++) {5
if (values[i] == target) return i;6
}7
return -1;8
}9
int main(void) {10
int values[] = {5, 2, 7};11
printf("%d\n", find(values, 3, 7));12
assert(find(values, 0, 7) == -1);13
assert(find(values, 3, 9) == -1);14
return 0;15
}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Create three elements. | values = [5, 2, 7] | — | |
| Index 0 does not match 7. | i = 0, value = 5 | — | |
| Index 1 does not match. | i = 1, value = 2 | — | |
| Index 2 matches; return it. | return = 2 | — | |
| Print the found index. | return = 2 | 2 | |
| Check zero-length and missing-target cases. | return = 2 | 2 |
Cost and common mistakes
O(n) worst-case time and O(1) auxiliary space.
- Using sizeof on the pointer parameter does not recover the array length.
- Passing a length larger than the actual array allows invalid reads.
Try it yourself
Search for 5 and then 4.
Reveal answer and reasoning
The results are 0 and -1 respectively.