Calculating string length in C involves scanning memory byte-by-byte until the null terminator (\0) byte is reached. This guide compares POSIX strlen() from <string.h> with custom pointer-arithmetic length functions and clarifies the key differences between strlen() and sizeof.
Standard strlen() vs Custom Implementation
#include <stdio.h>
#include <string.h>
// Custom string length using pointer arithmetic
size_t custom_strlen(const char *s) {
const char *p = s;
while (*p != '\0') {
p++;
}
return (size_t)(p - s); // Difference between pointers yields byte count
}
int main(void) {
char msg[50] = "Linux Kernel Systems";
printf("POSIX strlen(): %zu\n", strlen(msg)); // Output: 20
printf("custom_strlen(): %zu\n", custom_strlen(msg)); // Output: 20
printf("sizeof(msg): %zu\n", sizeof(msg)); // Output: 50 (Buffer Capacity)
return 0;
}
Comments and corrections