Strings are one of the fundamental building blocks in C and other major programming languages.

This quick guide will walk you through using one useful string function: strcat.

The strcat function allows you to concatenate or join two strings to form a single string value.

Basic Usage

The general syntax for this command is:

char *strtcat(char *destination_string, const char *source_string);

The strcat function accepts two arguments:

  1. The destination – Describes the destination string
  2. Source – Describes the source string.

The strcat command will concatenate the source and the destination strings, then store the result to the destination string.

NOTE: The strcat function is defined in the string.h header file. Hence, you need to include the strings header file using the clause:

Quick Example

The following sample code describes how the strcat function works.

#include

#include

int main () {


    char string1[10] = “Hello,”, string2[10] = “world”;

In the above example, printing the value of the destination string, in this case, strin1, shows the value of the two concatenated values as:

NOTE: Ensure the size of the destination string can hold the full concatenated string to avoid a segmentation fault, as shown in the example below:

#include

#include

int main () {


    char string1[5] = “Hello”, string2[5] = “world”;


    // join the strings


    strcat(string1, string2);


    printf(string1);

}

Since the size of the destination string, string1, is smaller than the resulting concatenated string, the program will quit with a segmentation fault, as shown in the output below:

Program received signal SIGSEGV, Segmentation fault.

NOTE: The strcat function is sensitive to the order of passed parameters; the first value represents the destination string while the second represents the source string.

Closing Up

In this quick tutorial, you learned how to use and work with the strcat command in C. To learn more, use the reference guide or check the Linux Programmers Manual.

About the author

<img alt="" data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/john-150×150.png6126590a51a13.jpg" height="112" src="data:image/svg xml,” width=”112″>

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list