C Programming

Strcat in C

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:

#include <string.h>

Quick Example

The following sample code describes how the strcat function works.


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:

int main () {
    char string1[5] = "Hello", string2[5] = "world";
    // join the strings
    strcat(string1, string2);

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

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