Open In App

C Program to Concatenate Two Strings Using a Pointer

Last Updated : 28 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Concatenating two strings means appending one string at the end of another string. While the standard library provides strcat() for concatenation, this article will demonstrate how to concatenate two strings using pointers.

To concatenate two strings using pointers, traverse the first string to its null terminator and then start appending characters from the second string until its null terminator is reached.

C
#include <stdio.h>

void concat(char *s1, char *s2) {
  
    // Move pointer to the end of first string
    while (*s1) s1++;

    // Append each character of the second string
    while (*s2) {
        *s1 = *s2;
        s1++;
        s2++;
    }

    // Null-terminate the concatenated string
    *s1 = '\0';
}

int main() {
    char s1[100] = "Hello, ";
    char s2[] = "World!";

    // Call the concatenation function
    concat(s1, s2);

    printf("%s\n", s1);
    return 0;
}

Output
Hello Geeks

Explanation: The pointer s1 is incremented to move it to the end of the first string. Then characters from s2 are copied to the position pointed by s1. The pointer is incremented for both strings after each character is copied. After all characters from s2 are appended, a null terminator ('\0') is added at the end to complete the concatenated string.


Next Article

Similar Reads