Course contentsShow
← C
Lesson 425 of 1,2196. Arrays and StringsFree lesson

Concatenating strings with `strcat`

Concatenating strings with strcat

What you'll learn: How to join two strings together by appending the contents of one to the end of another using the strcat function.

The logic of "tacking it on"

In C, you cannot simply use the + sign to combine two strings like you might in other languages. Instead, we use a function from the <string.h> library called strcat (short for "string concatenation").

Think of strcat like adding a trailer to a truck. You have your lead vehicle (the destination string) and you are hitching a second vehicle (the source string) onto the back of it. The first string gets longer, while the second string remains unchanged.

How strcat works

The function takes two arguments: strcat(destination, source);.

When this line runs, C looks for the null terminator (\0) at the end of the destination string. It starts overwriting at that exact spot with the characters from the source string. Once the source is finished, C automatically adds a new null terminator at the very end to seal the new, longer string.

Coding the connection

Here is how you combine a first name and a last name:

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

int main() {
    // 1. Destination must be large enough to hold both strings!
    char greeting[50] = "Hello, ";
    char name[] = "Alice!";

    // 2. Append 'name' to the end of 'greeting'
    strcat(greeting, name);

    printf("%s", greeting); // Outputs: Hello, Alice!

    return 0;
}

The "Golden Rule" of strcat

The most important thing to remember is space. In the example above, greeting was declared with a size of 50, even though "Hello, " is quite short.

If you try to concatenate a long string into a destination array that is too small, your program will start writing data into memory it doesn't own. This is called a buffer overflow and it will cause your program to crash or behave unpredictably. Always ensure the destination array has enough "slots" to hold its original text, the new text, and that final hidden \0 character.

Key takeaway

Use strcat(dest, src) to append the source string to the destination, ensuring the destination array is large enough to hold the combined result.