TutorialStudyMite

Concatenate strings in C

PPooja Rao5 min read
Beginner friendly

Track completion, mastery, and revision.

Introduction to String Concatenation

In C programming, concatenation refers to the process of joining two strings together end-to-end. For example, if you concatenate the string "Hello " and the string "World", the result is a new, single string: "Hello World".

This operation is sometimes conceptually referred to as the "binary addition" of strings. In this guide, we will explore three different ways to concatenate strings in C:

  1. Using standard library functions (strcat and strncat).
  2. Using custom loops (without library functions).
  3. Using pointers.

Approach 1: Using Standard Library Functions (strcat and strncat)

The simplest and most common way to concatenate strings in C is by using the built-in functions defined in the <string.h> header file: strcat() and strncat().

💡 Clarification: A common misconception is that strcat and strncat are non-standard or compiler-specific. In reality, both are part of the ISO/ANSI C Standard Library and are fully supported by all standard-compliant compilers (such as GCC, Clang, and MSVC). They are highly portable and recommended for standard development.

Syntax

1. strcat

char *strcat(char *destination, const char *source);
  • How it works: Appends a copy of the source string to the end of the destination string. The null terminator (\0) of the destination string is overwritten by the first character of the source string, and a new null terminator is appended to the end of the final string.
  • Return Value: A pointer to the destination string.

2. strncat

char *strncat(char *destination, const char *source, size_t n);
  • How it works: Appends up to n characters from the source string to the destination string. This function is much safer because it helps prevent buffer overflow vulnerabilities by limiting the number of characters copied.
  • Return Value: A pointer to the destination string.

Code Example

When reading strings using functions like fgets(), the trailing newline character (\n) is kept. To ensure clean concatenation, we should strip this newline character.

#include <stdio.h>
#include <string.h> // Required for strcat and strncat

int main() {
    char string1[100], string2[100];

    printf("Enter String 1: ");
    fgets(string1, sizeof(string1), stdin);
    // Strip trailing newline character if present
    string1[strcspn(string1, "\n")] = '\0';

    printf("Enter String 2: ");
    fgets(string2, sizeof(string2), stdin);
    string2[strcspn(string2, "\n")] = '\0';

    // Concatenate string2 to the end of string1
    strcat(string1, string2);

    printf("Concatenated string: %s\n", string1);

    return 0;
}

Output

Enter String 1: Hello 
Enter String 2: World!
Concatenated string: Hello World!

Alternative Variations

Appending Only a Specific Number of Characters

If you only want to append the first 3 characters of string2 to string1, you can use strncat:

strncat(string1, string2, 3);
printf("Using strncat (3 chars): %s\n", string1);

Approach 2: Manual Concatenation Using Loops

If you want to understand how concatenation works under the hood, or if you are working in an environment where the standard library is restricted, you can implement concatenation manually using loops.

Algorithm

  1. Read two strings, str1 (destination) and str2 (source).
  2. Find the length of str1 to locate its end.
  3. Iterate through str2 character-by-character and append each character to the end of str1.
  4. Manually append the null-terminator (\0) to seal the concatenated string.

Code Example

In this example, we use dynamic memory allocation with malloc and the POSIX getline() function to handle input.

#include <stdio.h>
#include <stdlib.h> // Required for malloc and free

int main() {
    char *str1, *str2;
    size_t size = 100;
    ssize_t bytes_read;

    printf("Enter first string: ");
    str1 = (char *)malloc(size * sizeof(char));
    bytes_read = getline(&str1, &size, stdin);

    // getline() includes the newline character '\n'. 
    // We start overwriting from the newline's index to keep the string on one line.
    int i = bytes_read - 1; 

    printf("Enter second string: ");
    str2 = (char *)malloc(size * sizeof(char));
    getline(&str2, &size, stdin);

    // Copy characters from str2 to the end of str1
    int j = 0;
    while (str2[j] != '\0') {
        str1[i] = str2[j];
        i++;
        j++;
    }
    
    // Null-terminate the final concatenated string
    str1[i] = '\0';

    printf("After concatenation: %s", str1);

    // Free dynamically allocated memory
    free(str1);
    free(str2);

    return 0;
}

Output

Enter first string: Hello! 
Enter second string: How are you?
After concatenation: Hello! How are you?

Approach 3: Concatenation Using Pointers

Pointers offer a highly efficient way to traverse and manipulate strings in C. This approach uses the same underlying logic as the loop method but uses pointer arithmetic instead of array indexing.

Code Example

#include <stdio.h>
#include <stdlib.h>

void concatenate(char *dest, const char *src) {
    // 1. Move the dest pointer to the end of the destination string
    while (*dest) {
        dest++;
    }

    // 2. Backtrack by 1 to overwrite the trailing newline character from getline()
    dest--; 

    // 3. Copy characters from src to dest
    while (*src) {
        *dest = *src;
        dest++;
        src++;
    }

    // 4. Null-terminate the destination string
    *dest = '\0';
}

int main() {
    char *str1, *str2;
    size_t size = 100;

    printf("Enter first string: ");
    str1 = (char *)malloc(size * sizeof(char));
    getline(&str1, &size, stdin);

    printf("Enter second string: ");
    str2 = (char *)malloc(size * sizeof(char));
    getline(&str2, &size, stdin);

    // Perform pointer-based concatenation
    concatenate(str1, str2);

    printf("After concatenation: %s", str1);

    // Clean up memory
    free(str1);
    free(str2);

    return 0;
}

Output

Enter first string: Hello! 
Enter second string: Bye!
After concatenation: Hello! Bye!

⚠️ Safety Tip: Always ensure that the destination buffer (str1 or dest) has allocated enough memory to hold the combined length of both strings plus the null-terminator. Failing to do so will result in undefined behavior or segmentation faults.

Finished reading?

Was this helpful?

Your feedback shapes better tutorials for everyone.