September 26, 2020

strcat function from string.h header file implementation in C

In this blog, I provide my own implementation for strcatĀ function in string.h header file.

You can watch the video, where I code this implementation.

The logic is very simple, I allocate a block of memory just enough to hold the concatenated strings.

First, I check for the validity of the first string, if the string is a valid strig , then I copy the first string in the new memory block, while copying the first string, I end up copying the NULL byte.

So, I check for the presence of the second string, it is there or not, If a second string is there then I remove the NULL byte copied from the first string. And, I copy the second string into theĀ newString with the NULL value.

And, at the end I return the newString , which has all the strings provided by the user.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

char * strcatImpl_1(char * restrict firstString, char * restrict secondString){
    int const noOfCharsInFirstString = firstString == NULL ? 0 : strlen(firstString);
    int const noOfCharsInSecondString = secondString == NULL ? 0 : strlen(secondString);
    
    if(0 == noOfCharsInFirstString && 0 == noOfCharsInSecondString) return NULL;

    char * const newString = (char *) 
                              (noOfCharsInFirstString == 0
                                 ? malloc(sizeof(char) * (noOfCharsInSecondString + 1))
                     : noOfCharsInSecondString == 0 
                     ? malloc(sizeof(char) * (noOfCharsInFirstString + 1))
                     : malloc(sizeof(char) * (noOfCharsInFirstString + noOfCharsInSecondString + 1))
                  );

    if(NULL == newString) return NULL;

    char * iterator = newString;
    if(0 != noOfCharsInFirstString) { 
        while((*iterator++ = *firstString++) != '\0'); 
        if(0 != noOfCharsInSecondString) --iterator;
    }
    
    if(0 != noOfCharsInSecondString) { while((*iterator++ = *secondString++) != '\0'); }

    return newString;
}

int main(int argc, char** argv){
    char* const slogan = strcatImpl_1("Jai!!!", "Shree Ram");
    printf("=> %s \n", slogan);
    if(NULL != slogan && '\0' != *slogan) free(slogan);
    return 0;
}

 

Tagged on: