Iterating strings until \0 with pointers
What you'll learn: How to use pointer arithmetic to traverse a string by looking for the null terminator.
In C, a string isn't a special data type; it is simply an array of characters ending with a special marker called the null terminator ('\0'). Because pointers store memory addresses, we can use them as "scouts" that move from one character to the next until they hit that final zero marker.
The "Walking" Analogy
Imagine a row of houses on a street. Each house has a letter painted on the door. You are standing in front of the first house, and your goal is to walk down the line until you reach a house with a blank door.
In this scenario, the houses are your memory addresses, and you are the pointer. Every time you take a step, you "increment" your position to the next address. You don't need to know how many houses there are in advance; you just keep moving as long as the door you’re looking at isn't blank.
Using a Pointer to Loop
Instead of using an integer index like i (e.g., str[i]), we can use a pointer to point directly to the current character. By using the increment operator (ptr++), we move the pointer to the next memory address. To see what is inside that address, we dereference it with *ptr.
Here is how you iterate through a string using only a pointer:
#include <stdio.h>
int main() {
char greeting[] = "Hello!";
char *ptr = greeting; // Start at the first character
// While the character at the current address is NOT the null terminator
while (*ptr != '\0') {
printf("Current char: %c\n", *ptr);
ptr++; // Move to the next memory address
}
return 0;
}
Why This Matters
When you pass a string to a function, C actually passes a pointer to the first character. By using while (*ptr != '\0'), you can process strings of any length without needing to know the size of the array beforehand. The pointer simply follows the trail of characters until it hits the "wall" of the null terminator.
Experienced C programmers often shorten this to while (*ptr). Since \0 has a numerical value of 0 (false), the loop naturally stops when it reaches the end of the string.
Key takeaway
You can traverse a string by incrementing a pointer and checking its dereferenced value against the null terminator (\0).