Concatenate Two Strings Using a Pointer in C

To concatenate two strings using a pointer in C, follow the below steps:

  • Make two character arrays (strings): the first one for the first string you want to concatenate and the other one for the second string.
  • Create pointers that you will be using to navigate through the first string characters.
  • Use a loop to traverse the first string until the null-terminator (‘\0’) is encountered.
  • Once the null-terminator is found, use the pointer to append the characters of the second string to the end of the first string.
  • Ensure that the resulting string is null-terminated.

Note: Make sure that the first string contains enough space to add the second string.

C Program to Concatenate Two Strings Using a Pointer

C




// C Program to Concatenate Two Strings Using a Pointer
#include <stdio.h>
  
void concatenateStrings(char* str1, const char* str2)
{
    // Find the end of the first string
    while (*str1 != '\0') {
        str1++;
    }
  
    // Copy characters from the second string to the end of
    // the first string
    while (*str2 != '\0') {
        *str1 = *str2;
        str1++;
        str2++;
    }
  
    // Ensure the resulting string is null-terminated
    *str1 = '\0';
}
  
// Driver Code
int main()
{
    char str1[50] = "Hello";
    const char str2[] = " w3wiki!";
  
    concatenateStrings(str1, str2);
  
    printf("Concatenated String: %s\n", str1);
  
    return 0;
}


Output

Concatenated String: Hello w3wiki!

Time Complexity: O(N + M), where N and M is the length of the first and second string.
Space Complexity: O(1)



C Program to Concatenate Two Strings Using a Pointer

In C, concatenation of strings is nothing but it is the process of combining two strings to form a single string. If there are two strings, then the second string is added at the end of the first string. In this article, we are going to learn how to concatenate two strings using a pointer in C.

Example:

Input:
str1 = "Hello";
str2 = " w3wiki!";

Output:
Hello w3wiki

Similar Reads

Concatenate Two Strings Using a Pointer in C

To concatenate two strings using a pointer in C, follow the below steps:...