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:
The strcat function accepts two arguments:
- The destination – Describes the destination string
- 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
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:
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:
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.