einval.net

Calculate the length of a string by iterating over each byte until you reach a NUL terminator (zero).

C

#include <stdio.h>

int strlen2(char *s) {
    int len = 0;

    // Copy pointer to avoid modifying the original
    char *s1 = s;

    // Track how many iterations are required to find '\0'
    while (s1++ && *s1 != '\0') {
        len++;
    }

    return len;
}

int main(int argc, char *argv[]) {
    char msg[] = "hello";
    int msg_len = strlen2(msg);
    print("Length of '%s' is %d\n", msg, msg_len);
    //
    // Length of 'hello' is 5
    //
}
Read more...

Let's write “Hello World!” for 16-bit DOS, 32-bit and 64-bit Linux...

Read more...