C Program to Concatenate Two Strings Using Pointers

1. Introduction

Concatenation is a common operation on strings, which involves combining two strings end-to-end. While there are library functions available in C for this purpose, understanding how to manually concatenate two strings using pointers provides a deeper insight into string operations and memory manipulation. In this article, we'll explore how to achieve this.

2. Program Overview

1. Declare two character arrays (strings).

2. Declare two character pointers.

3. Use the pointers to traverse the strings.

4. Concatenate the second string to the end of the first string using pointers.

3. Code Program

#include <stdio.h>

void concatenate(char *str1, char *str2) {
    // Move pointer to the end of the first string
    while (*str1) {
        str1++;
    }

    // Copy characters of the second string to the end of the first string
    while (*str2) {
        *str1 = *str2;
        str1++;
        str2++;
    }
    *str1 = '\0';  // Terminate the concatenated string
}

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

    // Input the strings
    printf("Enter the first string:\n");
    gets(string1);
    printf("Enter the second string:\n");
    gets(string2);

    // Concatenate the strings
    concatenate(string1, string2);

    // Display the concatenated string
    printf("Concatenated string: %s\n", string1);

    return 0;
}

Output:

Enter the first string:
Hello
Enter the second string:
World
Concatenated string: HelloWorld

4. Step By Step Explanation

1. The program starts with the declaration of two character arrays string1 and string2 which will store the input strings.

2. The function concatenate is defined to perform the concatenation using pointers. Within this function:

  • The pointer str1 is moved to the end of the first string. This is done by incrementing the pointer until it points to the null terminator of the first string.
  • Once at the end of the first string, the characters of the second string (str2) are copied to the end of the first string one by one.
  • After copying all characters from the second string, the concatenated string is terminated with a null character.

3. In the main function, the user is prompted to enter two strings. These strings are read using the gets function (Note: Using gets is generally discouraged due to potential buffer overflow issues, but it is used here for simplicity).

4. The concatenate function is then called with the two strings as arguments.

5. Finally, the concatenated string is displayed, showcasing the result of the concatenation.

Comments