Understanding strlen() Internally by Writing It From Scratch in C
Source: Dev.to
Introduction
strlen() is a predefined function used to determine the length of a given string.
Syntax
size_t strlen(const char *str);
Example
char str[6] = "hello";
size_t len = strlen(str); // len = 5
What Is a String in C?
In C, a string is not a distinct data type. It is an array of characters terminated by a null character ('\0'). The null character indicates the end of the string.
Header File
strlen() is declared in the <string.h> header file, which contains many standard library function declarations.
Implementing strlen() from Scratch
Prototype
int my_strlen(const char *str);
const char *str– a pointer to the first character of the string (the base address).constprevents modification of the string inside the function, helping avoid bugs.
Implementation
int my_strlen(const char *str)
{
int cnt = 0;
while (str[cnt] != '\0')
{
cnt++;
}
return cnt;
}
How It Works – Step by Step
- Argument Passing – The base address of the string is passed to the function.
- Counter Initialization –
cntis set to0and will count the characters. - Loop Condition – The loop continues while
str[cnt]is not the null character'\0'. - Pointer Arithmetic – Although we use
str[cnt], the compiler treats it as pointer arithmetic (*(str + cnt)). - Incrementing the Counter – Each iteration moves to the next character and increments
cnt. - Loop Termination – When
str[cnt]equals'\0', the condition becomes false, the loop ends, andcntholds the length of the string (excluding the null terminator).
Memory Representation
+---+---+---+---+---+---+
| h | e | l | l | o | \0|
+---+---+---+---+---+---+
^ ^
| |
base address null terminator
Why It Returns the Length of the String
- Every character before the null terminator is counted.
- The null character itself is not counted.
- Counting stops exactly at the end of the string, giving the true length.
Final Understanding
By writing strlen() from scratch, you can see:
- How strings are stored in memory as a sequence of characters ending with
'\0'. - The importance of the null character in marking the end of a string.
- How pointer arithmetic and simple loops are used for string traversal in C.