Example 1 — Search that returns NULL when not found
Check the result before dereferencing.
#include <stdio.h>
int *find(int *a, int n, int key) {
for (int i = 0; i < n; i++) {
if (a[i] == key) return &a[i];
}
return NULL;
}
int main(void) {
int data[] = {4, 8, 15};
int *r = find(data, 3, 8);
if (r) printf("found %d at index %td\n", *r, r - data);
r = find(data, 3, 99);
if (!r) printf("99 not found\n");
return 0;
} How It Works
- A hit returns the element's address.
- A miss returns
NULL. if (r)guards the dereference;r - dataconverts the pointer to an index.
