- How a single pointer walks a string until it hits the null terminator
- How pointer subtraction gives the length in one expression
- Why
strlenis O(n) — it must scan the whole string - Why the function takes
const char *and returnssize_t - The difference between
sizeofon an array and the actual string length
How Pointer-Based String Length Works
A C string is a sequence of characters ending with a null terminator, '\0'. Its length is the number of characters before the terminator — not counting the terminator itself. For "Hello", the length is 5, even though the string occupies 6 bytes in memory (the 5 characters plus the '\0'). This is why strlen("Hello") returns 5, and it's why sizeof("Hello") returns 6 — the two are measuring different things.
Because C doesn't store the length anywhere, the only way to find it is to walk the string from the beginning until you hit the terminator. That's exactly what a pointer is good at. Save the starting address in start, move the pointer forward one character at a time with s++, and stop when *s is '\0'. The number of steps you took is the length — and in pointer arithmetic, "the number of steps" is exactly s - start. The subtraction gives the count directly, with no counter variable needed.
The pointer-difference trick is the heart of strlen. It works because pointer subtraction between two pointers into the same array returns the number of elements between them — not bytes, but elements of the pointer's type. For a char *, each element is one byte, so s - start is the byte count, which is the character count. This is the same operation you'd get from a counter that increments on every step, but expressed in a single expression after the loop. The loop itself doesn't need to count — it just needs to walk.
💡 In one line: Save the start, walk the pointer to the '\0', and return s - start — the number of characters moved is the length of the string.
The Three Steps of the Length
| Step | Pointer operation | Effect |
|---|---|---|
| 1. Save the start | const char *start = s; | Preserves the base address for the final subtraction |
| 2. Walk to the terminator | while (*s != '\0') s++; | s ends up pointing at the null terminator |
| 3. Return the difference | return (size_t)(s - start); | The number of characters between start and end — the length |
The return type is size_t, which is the standard type for object sizes and string lengths. It's an unsigned integer type defined in <stddef.h> (and pulled in by <stdio.h>, <string.h>, etc.), large enough to hold the size of any object. strlen returns size_t, so matching that convention is important for interoperability. A length can't be negative, so unsigned is the natural choice — but it means you must be careful not to subtract a larger length from a smaller one when using the result in arithmetic, because unsigned underflow wraps to a huge number.
The function takes const char * because it only reads the string. This lets callers pass string literals (which are read-only) and const string variables without warnings, and it documents at the type level that the string won't be modified. It's the same signature as standard strlen, which also takes const char *. Taking a non-const pointer would still work for writable strings, but it would be wrong for literals — and there's no downside to const here.
Complete C Program
Program: calculate the length of a string using a function and pointers
#include <stdio.h>
#include <stddef.h> /* for size_t */
/* Return the length of the string s (not counting the null terminator).
The string is read but not modified. */
size_t str_length(const char *s) {
if (s == NULL) {
return 0;
}
const char *start = s; /* remember where we started */
while (*s != '\0') {
s++; /* advance one character */
}
return (size_t)(s - start); /* pointer difference = length */
}
int main(void) {
const char *tests[] = {
"Hello, World!",
"C",
"",
"12345",
"Pointers are powerful",
"a b c",
" leading and trailing "
};
int n = (int)(sizeof(tests) / sizeof(tests[0]));
printf("String length results:\n");
printf("-----------------------\n");
for (int i = 0; i < n; i++) {
printf(" len(%-25s) = %zu\n", tests[i], str_length(tests[i]));
}
/* Interactive length */
char buf[256];
printf("\nEnter a string: ");
if (scanf("%255[^\n]", buf) == 1) {
printf(" length of \"%s\" = %zu\n", buf, str_length(buf));
}
return 0;
}
Program Output
String length results:
-----------------------
len(Hello, World! ) = 13
len(C ) = 1
len( ) = 0
len(12345 ) = 5
len(Pointers are powerful ) = 20
len(a b c ) = 5
len( leading and trailing ) = 23
Enter a string: Pointer arithmetic
length of "Pointer arithmetic" = 18
The output covers a range of cases: a normal string with punctuation (13), a single character (1), an empty string (0), a string of digits (5), a longer phrase (20), a string with internal spaces (5), and a string with leading and trailing spaces (23). The interactive run with "Pointer arithmetic" confirms the count on a fresh input: P-o-i-n-t-e-r (7) + space (1) + a-r-i-t-h-m-e-t-i-c (10) = 18. Every one of these is computed by the same function — no special cases, no length lookups. The function simply walks until it sees '\0'.
Step-by-Step Explanation
Let's walk through the pointer mechanics.
1. The function signature
size_t str_length(const char *s) takes a pointer to a const char and returns size_t. This is the same signature as standard strlen, and the type choices are deliberate. const char * documents that the function only reads the string — it can be called with string literals, const buffers, or writable arrays, and the compiler enforces that the function won't modify the bytes. size_t is the standard "size or length" type: unsigned, wide enough to hold the length of any object, and interoperable with standard library functions that expect a length.
2. The null guard
if (s == NULL) return 0; protects against a null pointer. Standard strlen(NULL) is undefined behaviour — it usually crashes — because the function has no way to know where to stop if the pointer doesn't point at a string. Guarding by returning 0 is a safe, deterministic choice, though some libraries instead assert or document that NULL is not allowed. Either convention is fine; the important thing is to pick one and document it. Returning 0 makes the function "total" — defined for every input — which is convenient for beginners.
3. Saving the start
const char *start = s; copies the initial pointer value before the loop begins. This is essential: after the loop, s will point at the null terminator, and we need the original base address to compute the difference. start is declared const char * for consistency with the parameter, though it could be char * — the const just documents that we won't write through it.
4. The walk
while (*s != '\0') s++; is the entire length algorithm. On each iteration, dereference s and check whether it's the null terminator. If not, advance the pointer. When *s is '\0', the loop stops and s points at the terminator. No counter, no index, no length variable — just a pointer moving through memory.
5. The pointer difference
return (size_t)(s - start); computes the length. In C, subtracting two pointers into the same array yields the number of elements between them, as a ptrdiff_t (a signed integer type). For a char *, each "element" is one character, so the difference is the number of characters traversed — which is exactly the length. The cast to size_t is needed because str_length returns size_t, and ptrdiff_t is signed. The length can never be negative (the loop only moves forward), so the cast is safe.
6. Tracing "Hello, World!"
start = s at index 0 ('H'). The loop advances s through 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', and stops at index 13 ('\0'). The difference s - start is 13, which is the length. The terminator itself is not counted — the loop stops at it, not past it. If the loop had been written while (*s) s++; followed by an extra s++, it would have counted the terminator too, giving 14 — a classic off-by-one bug.
7. Tracing the empty string
For "", s points directly at '\0'. The loop condition *s != '\0' is false immediately, so the loop body never runs. The return is s - start, where both s and start point at the same address — so the difference is 0. Correct: an empty string has length 0. This is another case where the loop condition handles the edge naturally, without an explicit check.
8. Tracing the single character "C"
s points at 'C'. The loop body runs once: s++ moves to the terminator. Then *s != '\0' is false, so the loop stops. s - start is 1. Correct: a single-character string has length 1. This works because the loop counts steps, not characters, and the step from index 0 to index 1 is one step — regardless of what the character at index 0 is.
9. Why strlen is O(n)
The only way to find the length of a C string is to scan it until the terminator, because the length isn't stored anywhere. So strlen — and any function like it — must be O(n) in the length of the string. There's no O(1) version in standard C, because there's no length field to read. This is why some performance-sensitive code either stores lengths alongside strings (as a "length + data" struct, or in a separate variable) or uses a different string representation entirely. But for most code, the O(n) cost is small and the simplicity of null-terminated strings is worth it.
10. sizeof vs str_length
A common beginner question: why not just use sizeof? The answer is that sizeof measures the size of the array or pointer as declared, not the length of the string it contains. For char buf[100] = "Hello";, sizeof(buf) is 100, but str_length(buf) is 5. For const char *p = "Hello";, sizeof(p) is the size of a pointer (typically 8 bytes on 64-bit systems), while str_length(p) is still 5. sizeof is a compile-time constant; str_length must run at runtime. They measure fundamentally different things.
11. Why no counter variable
The classic loop version uses a counter: size_t len = 0; while (*s) { len++; s++; } return len;. That works, but it uses an extra variable. The pointer-difference version is more elegant: the loop doesn't need to count anything, because the pointers themselves encode the position. After the loop, s - start tells you how far you've come. This is a general pattern — whenever you're measuring distance in memory, subtracting pointers is often cleaner than maintaining an explicit counter. It's also exactly how strlen is implemented in most standard libraries (though some optimized versions process multiple bytes at a time).
12. Complexity
The loop runs once per character, so time is O(n) where n is the string length. Space is O(1) — a single pointer, regardless of length. This is optimal for null-terminated strings: there's no way to know the length without scanning to the terminator, so O(n) time is the best possible. The function does no unnecessary work — every character is examined exactly once, and the return is one subtraction.
🎯 Remember this: Length of a C string = walk a pointer to the '\0', then subtract the starting address. The terminator itself is not counted, empty strings have length 0, and a single character has length 1. The function takes const char * (read-only) and returns size_t (unsigned, wide enough for any string), matching standard strlen.
Frequently Asked Questions
1. Why not just use strlen from <string.h>?
You could — strlen does exactly this. But the assignment asks you to implement the length function yourself, and doing so teaches you what the standard library function does under the hood: the pointer walk, the null terminator, the pointer-difference trick, and the size_t return type. Understanding these details matters when you write string code that must interoperate with strlen's contract (e.g., a buffer that must be at least strlen(s) + 1 bytes to hold a copy). And it's a great way to internalise pointer arithmetic.
2. Why does the function return size_t instead of int?
Because size_t is the type the C standard uses for object sizes and string lengths, and strlen returns size_t. It's an unsigned integer type wide enough to represent the size of any object the implementation supports — on a 64-bit system, usually 64 bits. Using size_t matches strlen's signature, so the function can be used interchangeably with the standard one. Returning int would work for small strings but could overflow for huge ones and would produce warnings when used in sizeof-related arithmetic. Lengths are non-negative, so an unsigned type is semantically appropriate.
3. Why does the loop stop at '\0' and not ' '?
Because '\0' (the null byte, value 0) is the terminator that marks the end of a C string, while ' ' (space, value 32) is just an ordinary character. A string can contain any number of spaces — "a b c" has length 5 including two spaces — so stopping at a space would give the length of the first word, not the whole string. The function correctly stops at the null terminator, which is the only character that can't appear inside a valid C string (by definition — if a null appears mid-string, the string ends there for all string functions).
4. What happens if I pass a string with an embedded null byte?
The function returns the length up to the first null byte, because that's where the loop stops. This is the standard behaviour of all C string functions — strlen, strcmp, strcpy, and so on all stop at the first '\0'. So a buffer like {'a', 'b', '\0', 'c', 'd', '\0'} has length 2, not 4, from the function's perspective. If you need to work with binary data that may contain null bytes, use memcpy/memcmp/memchr (which take explicit lengths) rather than the string functions. This distinction between "text" and "binary data" is important in C.
5. Why is sizeof different from strlen?
Because they measure different things. sizeof is a compile-time operator that returns the size (in bytes) of a type or object as declared. For char buf[100] = "Hello";, sizeof(buf) is 100 — the size of the array — regardless of how many characters are actually used. strlen(buf) is 5 — the number of characters before the terminator. For a pointer, sizeof(p) is the size of the pointer itself (typically 8 bytes), not the length of what it points at. So sizeof answers "how much memory does this object occupy?" while strlen answers "how many characters are in this string?" They're related but fundamentally different.
6. What is the time and space complexity?
Time is O(n), where n is the string length. The loop visits each character exactly once — there's no way to compute the length of a null-terminated string without scanning to the terminator, so O(n) is optimal. Space is O(1): a single pointer variable, regardless of the string's length. The function is as efficient as it can be for null-terminated strings, and its design (no counter, no auxiliary storage) reflects that.
💡 Tip: Once this works, try implementing other classic string functions with the same pointer walk: strcpy (copy one string to another), strcat (append), strcmp (compare), and strchr (find a character). They all use the same basic idiom — a pointer or two walking through memory — with different comparison and termination rules. Mastering the length function is a good foundation for the others, because almost every string algorithm needs to know how far it can go before the string ends.