C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Concatenate strings using pointers

C Program: Concatenate strings using pointers

C

#include <stdio.h>

 

int main() {

    char str1[200], str2[100];

    char *ptr1, *ptr2;

 

    // Input two strings

    printf("Enter first string: ");

    fgets(str1, sizeof(str1), stdin);

    printf("Enter second string: ");

    fgets(str2, sizeof(str2), stdin);

 

    // Initialize pointers

    ptr1 = str1;

    ptr2 = str2;

 

    // Move ptr1 to the end of str1

    while (*ptr1 != '\0') {

        if (*ptr1 == '\n') { // remove newline from fgets

            *ptr1 = '\0';

            break;

        }

        ptr1++;

    }

 

    // Copy str2 to the end of str1

    while (*ptr2 != '\0') {

        if (*ptr2 == '\n') { // remove newline from fgets

            ptr2++;

            continue;

        }

        *ptr1 = *ptr2;

        ptr1++;

        ptr2++;

    }

 

    *ptr1 = '\0'; // Null terminate the concatenated string

 

    // Display result

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

 

    return 0;

}

Output

 
OUTPUT 1 :
Enter first string: IT
Enter second string: Developer
Concatenated string: ITDeveloper

Explanation

  • The program uses pointers to concatenate two strings manually, without using strcat().
  • ptr1 moves to the end of the first string.
  • Then, characters from the second string (via ptr2) are copied one by one to the end of the first string.
  • The final string is null-terminated.