C program for String Concatenation using strcat function

The strcat() function appends the src string to the dest string, overwriting the terminating null byte (‘\0’) at the end of dest, and then adds a terminating null byte. The strings may not overlap, and the dest string must have enough space for the result. If dest is not large enough, program behavior is unpredictable
The strcat() and strncat() functions return a pointer to the resulting string dest.

The declaration of strcat looks like,

 $ char *strcat(char *dest, const char *src); 
 $ vim strcat_test.c 
#include <stdio.h>
#include <string.h>

int main(void) {
        char str[128]="hello";
        printf("First string: \"%s\" : length:%d \n", str, strlen(str));
        printf("String to append: \"%s\" : length:%d \n", "world", strlen("world"));
        printf("Concatnated string: %s \n", strcat(str, "world"));

        printf("strlen of final string = %d\n", strlen(str));
        return 0;
}
 $ $ gcc -o strcat_test strcat_test.c 
 $ ./strcat_test

First string: "hello" : length:5 
String to append: "world" : length:5 
Concatnated string: helloworld 
strlen of final string = 10

Follow Lynxbee

Leave a Reply / Ask Question