Lesson 3 of 23
rev
The rev Command
rev reverses each line of its input. Each line is printed backwards; the line order stays the same.
$ echo "hello" | rev
olleh
$ printf "cat\ndog\n" | rev
tac
god
Your Implementation
Write void my_rev(const char *s) that reverses each line.
The algorithm: scan forward through the string. When you hit a \n (or end of string), you know where the current line ends. Walk backwards from end to start, printing each character, then print the newline.
void my_rev(const char *s) {
const char *line_start = s;
while (*s) {
if (*s == '\n') {
// Print characters from (s-1) down to line_start
const char *p = s - 1;
while (p >= line_start) {
putchar(*p);
p--;
}
putchar('\n');
line_start = s + 1;
}
s++;
}
}
Pointer Arithmetic
This lesson is about pointer arithmetic — a core C skill:
const char *line_start = s— pointer to the start of the current lineconst char *p = s - 1— pointer one character before the\np--— move the pointer one character earlierp >= line_start— stop when we have passed the start
Pointers and array indices are interchangeable in C: p[0] and *p are the same thing.
Your Task
Implement my_rev so it prints each line reversed.
TCC compiler loading...
Loading...
Click "Run" to execute your code.