Once records are stored, the next question is "where is the record for reading?" A linear search visits active elements one by one until it finds a match. The loop is simple; the contract around it is where the decisions are. How do you compare text? What do you return when nothing matches, given that every size_t value is a possible index? And how long does the answer stay true, once the collection can grow and shrink? Get those wrong and a search can report the wrong record, or hand back a pointer that dangles after the next append.
Predict and run
Read the program before pressing Run. Write down its output.
#include <stdio.h>
#include <string.h>
int main(void) {
const char *topics[3] = {"reading", "coding", "reading"};
size_t found = 0;
for (size_t i = 0; i < 3; ++i) { if (strcmp(topics[i], "reading") == 0) { ++found; } }
printf("%zu\n", found);
return 0;
}Check your prediction
2strcmp returns 0 when two strings contain the same characters, so two of the three topics match. The loop visits only indexes below the count, the same bound rule as every other loop in this course.
== compares addresses, strcmp compares text
A string in C is reached through a pointer, so a == b asks "do these point to the same place?", not "do they hold the same letters?". Records each own their own topic array, so two records with the same topic always live at different addresses. (Comparing the two arrays directly is such a common mistake that Clang rejects it under -Werror as "array comparison always evaluates to false", so this example compares pointers.)
#include <stdio.h>
#include <string.h>
int main(void) {
char first[24] = "reading";
char second[24] = "reading";
const char *a = first;
const char *b = second;
printf("a == b: %s\n", a == b ? "yes" : "no");
printf("strcmp == 0: %s\n", strcmp(a, b) == 0 ? "yes" : "no");
printf("coding before reading: %s\n", strcmp("coding", "reading") < 0 ? "yes" : "no");
return 0;
}a == b: no
strcmp == 0: yes
coding before reading: yesstrcmp returns a negative value, zero or a positive value. The sign says which string sorts first, comparing byte by byte. Only the sign is promised: one library returns -1, another returns the difference between the first unequal bytes. Test < 0, == 0 or > 0, never == -1. And strcmp requires both arguments to be terminated strings; a topic without its '\0' makes it read past the array.
Saying "not found"
Every size_t can be a valid index, so no index value naturally means "missing". Three common answers:
- Return
SIZE_MAXas a sentinel. Callers must remember to compare with it before indexing. - Return a pointer, with
NULLfor missing. Convenient, but the pointer has a lifetime problem, below. - Return a status and write the index through an out-parameter only on success. This is the course's choice, because the status sits in plain sight at every call site and failure leaves the out-parameter unchanged. The compiler won't warn about an ignored
int, as Day 1's contracts lesson showed, so reading the status is still the caller's job.
How long does a result stay valid?
A pointer into the collection expires when the block moves, which any successful growth may cause. An index survives growth, because realloc keeps elements in the same order. But an index does not survive a removal before it: after removing index 0, the record you found at index 2 is at index 1, and index 2 is a different record or no record. So the rule is: a search result is valid until the next operation that adds or removes records. If you need the record after that, search again.
A search must not modify
Declare the array parameter const Record records[]. That promises callers the function only reads, and the compiler enforces it:
size_t count_topic(const Record records[], size_t count) {
records[0].minutes = 0; /* error: cannot assign to a const-qualified object */
return count;
}A read-only query can then be called on any collection, including one another part of the program is only borrowing.
Practice
Your turn
Write int find_from(const Record records[], size_t count, const char *topic, size_t start, size_t *out_index). It searches from index start onward and, on a match, stores the index and returns 1. If there is no match, or start >= count, it returns 0 without writing. Use it in a loop to print every index where reading appears, then search for a missing topic and for a start past the end. Expected output: reading at 0, reading at 2, reading at 4, painting: not found, index still 4, start 9: not found, index still 4.
#include <stdio.h>
#include <string.h>
typedef struct { char topic[24]; int minutes; } Record;
/* Write find_from here. */
int main(void) {
const Record records[5] = {
{"reading", 25}, {"coding", 40}, {"reading", 10}, {"math", 30}, {"reading", 5},
};
size_t index = 0;
// Print every index of "reading", then the two not-found cases.
return 0;
}Hint 1: the idea
To find the next match after one at index i, search again from i + 1. The search itself rejects a start at or past the count, which is how the loop ends.
Hint 2: a first step
Write find_from and call it once from main with start 0: it should report index 0. Then decide, before writing the loop in main, what start the second call needs and what makes the loop stop.
Show one solution
#include <stdio.h>
#include <string.h>
typedef struct { char topic[24]; int minutes; } Record;
int find_from(const Record records[], size_t count, const char *topic,
size_t start, size_t *out_index) {
for (size_t i = start; i < count; ++i) {
if (strcmp(records[i].topic, topic) == 0) {
*out_index = i;
return 1;
}
}
return 0;
}
int main(void) {
const Record records[5] = {
{"reading", 25}, {"coding", 40}, {"reading", 10}, {"math", 30}, {"reading", 5},
};
size_t index = 0;
size_t start = 0;
while (find_from(records, 5, "reading", start, &index)) {
printf("reading at %zu\n", index);
start = index + 1;
}
if (!find_from(records, 5, "painting", 0, &index)) {
printf("painting: not found, index still %zu\n", index);
}
if (!find_from(records, 5, "reading", 9, &index)) {
printf("start 9: not found, index still %zu\n", index);
}
return 0;
}reading at 0
reading at 2
reading at 4
painting: not found, index still 4
start 9: not found, index still 4A start of 9 needs no special case: the loop condition i < count is false at once, so nothing is read past the array. index + 1 cannot overflow, because index is below count. The const parameter guarantees the search leaves the records alone. Next, you will pass the matching rule itself as a parameter, using a function pointer.
Completion is saved in this browser only. It does not measure mastery.