strcat() Function

The strcat() function concatenates two strings by appending the content of one string to the end of another. This results in a single, combined null-terminated string. The function works by overwriting the null terminator of the first string with the contents of the second, then adding a new null terminator at the end of the combined string.


Syntax of strcat()

</>
Copy
char *strcat(char *destination, const char *source);

Parameters

ParameterDescription
destinationPointer to the destination array, which must contain a null-terminated C string and be large enough to hold the concatenated result.
sourcePointer to the null-terminated C string that is to be appended to the destination string.

Return Value

The function returns a pointer to the resulting string, which is the same as the destination string.

Notes

It is important to note that the terminating null character of the first string is overwritten by the first character of the second string during the concatenation process, and a new null terminator is appended at the end. Also, the memory areas for the two strings should not overlap to avoid undefined behavior.


Examples for strcat()

Example 1: Basic String Concatenation

This example demonstrates how to use strcat() to append one string to another.

Program

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

int main() {
    char first[50] = "Hello, ";
    char second[] = "World!";
    
    // Concatenate second string onto first string
    strcat(first, second);
    
    printf("Concatenated string: %s\n", first);
    return 0;
}

Explanation:

  1. A character array first is initialized with the string "Hello, " and has ample space for additional characters.
  2. A second character array second is initialized with the string "World!".
  3. The strcat() function appends the content of the second string to the first.
  4. The resulting concatenated string is printed using printf().

Output:

Concatenated string: Hello, World!

Example 2: Building a Sentence by Concatenation

This example demonstrates how to concatenate multiple strings to form a complete sentence.

Program

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

int main() {
    char sentence[100] = "The quick brown ";
    char adjective[] = "fox ";
    char verb[] = "jumps over ";
    char object[] = "the lazy dog.";

    // Concatenate strings to form a full sentence
    strcat(sentence, adjective);
    strcat(sentence, verb);
    strcat(sentence, object);

    printf("Full sentence: %s\n", sentence);
    return 0;
}

Explanation:

  1. A character array sentence is initialized with the beginning of a sentence and is large enough to hold the full sentence.
  2. Additional strings are concatenated sequentially using strcat() to form a complete sentence.
  3. The complete sentence is printed using printf().

Output:

Full sentence: The quick brown fox jumps over the lazy dog.