September 26, 2020

strlen string.h function implementation in c

This is the implementation for strlen function that is present in the string.h header file of c standard library.

You can watch the youtube video for live implementation.

This is my way of implementing this function, this is not how the standard library implements it.

The basic idea is to use information of ‘\0’ termination in a string.

In The first implementation, I use a separate variable to keep the length of the string.

But in second case, I use pointer arithmetic operation to subtract memory value present in string variable from memory value present in the charIterator variable.

And, that difference is returned.

Full Source Code :-

#include<stdio.h>
#include<stddef.h>

//Implementation 1
int strlenImpl_1(char * restrict string){
    if(NULL == string) return -1;
    int length = 0; 
    while('\0' != *string++) ++length;
    return length;
}

//Implementation 2
ptrdiff_t strlenImpl_2(char * const restrict string){
    if(NULL == string ) return -1;
    char * charIterator = string;
    while(*charIterator++ != '\0');
    return charIterator - string - 1;
}

int main(int const argc, char **argv){
    char *firstName = "Anurag";
    printf("Length Of FirstName %d \n", strlenImpl_1(firstName));
    printf("Length Of FirstName %ld \n", strlenImpl_2(firstName));
    return 0;
}

 

Tagged on: