Pointer Assignment 20 — Concatenate Two Strings Using Pointers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Concatenate Two Strings Using Pointers — Joining Strings Without Library Functions

📑 On this page:
  • How Pointer-Based String Concatenation Works
  • The Three Steps of Concatenation
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to concatenate two strings using a user-defined function
  • How to move a pointer to the null character of a string
  • How to copy characters from one string to another using pointers
  • Why the destination array must be large enough to hold both strings
  • How to add the terminating null character after concatenation
  • How this manual method relates to the standard strcat() function

How Pointer-Based String Concatenation Works

Concatenation means joining two strings end to end. For example, if the first string is "Hello" and the second string is "World", then after concatenation the destination string becomes "HelloWorld".

In C, a string is an array of characters ending with the null character '\0'. To concatenate two strings manually, the program first finds the null character at the end of the destination string. Then it copies characters from the source string into the destination string, starting from that position.

The function uses two pointers: dest points to the destination string, and src points to the source string. First, dest is moved to the end of the destination string. Then, in a loop, each character from src is copied to dest, and both pointers are incremented. Finally, a null character is added to mark the end of the combined string.

💡 In one line: Move the destination pointer to its null character, copy each source character there, advance both pointers, and finish by adding '\0'.

Diagram showing two strings being concatenated using pointers in C

The Three Steps of Concatenation

Step Pointer operation Effect
1. Reach the end of the destinationwhile (*dest != '\0') dest++;dest now points to the null character of the first string
2. Copy the source stringwhile (*src != '\0') { *dest = *src; dest++; src++; }Each character of the source string is copied after the destination string
3. Terminate the result*dest = '\0';The combined string is properly ended

The destination array must have enough space to store both strings plus the final null character. For example, to concatenate a 5-character string and a 5-character string, the destination array must be able to hold at least 11 characters: 5 + 5 + 1.

This program does not use the library function strcat(). Instead, it implements the same logic manually using pointers, which helps you understand how C strings are stored and processed in memory.

Complete C Program

Program: concatenate two strings using pointers

#include <stdio.h>

#define MAX 200

/* Concatenate source string at the end of destination string. */
void concatenate_strings(char *dest, const char *src) {
    /* Move dest to the null character of the destination string */
    while (*dest != '\0') {
        dest++;
    }

    /* Copy characters from source to destination */
    while (*src != '\0') {
        *dest = *src;
        dest++;
        src++;
    }

    /* Add the terminating null character */
    *dest = '\0';
}

int main(void) {
    char str1[MAX];
    char str2[MAX];

    printf("Enter the first string: ");
    if (fgets(str1, sizeof(str1), stdin) == NULL) {
        printf("Invalid input.\n");
        return 1;
    }

    printf("Enter the second string: ");
    if (fgets(str2, sizeof(str2), stdin) == NULL) {
        printf("Invalid input.\n");
        return 1;
    }

    /* Remove trailing newline characters entered by fgets */
    char *p = str1;
    while (*p != '\0') {
        if (*p == '\n') {
            *p = '\0';
            break;
        }
        p++;
    }

    p = str2;
    while (*p != '\0') {
        if (*p == '\n') {
            *p = '\0';
            break;
        }
        p++;
    }

    concatenate_strings(str1, str2);

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

    return 0;
}
                                    

Program Output

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

Concatenated string: HelloWorld
                                

A second run, with strings containing spaces:

Enter the first string: Sankalan
Enter the second string: Data Tech

Concatenated string: SankalanData Tech
                                

In the first run, the function finds the null character after "Hello" and copies "World" from that position. In the second run, spaces inside the strings are preserved because fgets() reads the complete line, including spaces.

Step-by-Step Explanation

Let us understand how the function joins the two strings using pointers.

1. The function signature

void concatenate_strings(char *dest, const char *src) receives two character pointers. The dest pointer points to the destination string, which will contain the final combined result. The src pointer points to the source string, whose characters will be added at the end.

2. Moving to the end of the destination

The first loop, while (*dest != '\0') dest++;, moves dest forward until it reaches the null character. For example, if the destination string is "Hello", the pointer stops at the memory location just after the character 'o'.

3. Copying the source characters

The second loop copies one character at a time. The statement *dest = *src; copies the character pointed to by src into the location pointed to by dest. Then dest++ and src++ move both pointers to their next characters.

4. Adding the null character

When *src becomes '\0', the loop stops. At this point, dest points to the position where the combined string must end. The statement *dest = '\0'; adds the terminating null character.

5. Example trace

Suppose str1 = "Hello" and str2 = "World":

  • Initially, dest points to 'H' and src points to 'W'.
  • The first loop moves dest to the null character after "Hello".
  • The second loop copies 'W', 'o', 'r', 'l', and 'd' one by one.
  • After copying, str1 becomes "HelloWorld".
  • Finally, '\0' is added at the end.

6. Why the destination must be large enough

The destination array must have space for both strings and the final null character. If it is too small, the function will write beyond the array boundary. This is called a buffer overflow and can cause unpredictable behavior or a program crash.

7. Why const char *src is used

The source string is declared as const char *src because the function only reads from it. The const keyword prevents accidental modification of the source string inside the function.

8. Why fgets is used instead of scanf

fgets() can read strings containing spaces, while scanf("%s") stops at the first whitespace character. Because fgets() also stores the newline character, the program removes it before concatenation.

9. Manual concatenation vs strcat

The standard library function strcat(dest, src) performs the same operation. Our user-defined function performs the same steps manually: find the end of dest, copy src, and add '\0'. Writing it manually is useful for learning pointer traversal and string memory layout.

10. Complexity summary

If the destination string has m characters and the source string has n characters, the time complexity is O(m + n). The function must traverse the destination string to find its end and then traverse the source string to copy it. Space complexity is O(1) because the function uses only pointer variables and does not allocate extra memory.

🎯 Remember this: To concatenate strings using pointers, first move dest to its null character, then copy every character from src, and finally write '\0' at the end. Always ensure the destination array is large enough.

Frequently Asked Questions

1. What does concatenation mean in C?

Concatenation means joining two strings into one string. For example, concatenating "Hello" and "World" produces "HelloWorld". The second string is added immediately after the first string.

2. Why do we move the destination pointer to '\0'?

The null character marks the end of the destination string. The source string must be copied starting from that position; otherwise, it would overwrite characters of the destination string.

3. What happens if the destination array is too small?

If the destination array does not have enough space, the function may write beyond its boundary. This is a buffer overflow, which can corrupt memory, cause a crash, or create a security vulnerability.

4. Can this function concatenate a string with itself?

It can, but only if the destination array has enough extra space. For example, concatenating "abc" with itself requires space for "abcabc" plus the null character. Also, the source and destination must not overlap in an unsafe way.

5. How is this different from strcat()?

strcat() is a standard library function that concatenates strings automatically. This program performs the same task manually using pointer traversal. The manual version is useful for understanding how C strings and pointers work internally.

6. What is the time complexity of this program?

The time complexity is O(m + n), where m is the length of the destination string and n is the length of the source string. The function traverses the destination once to find its end and traverses the source once to copy it. Space complexity is O(1).

💡 Tip: After implementing this program, try writing a version that returns the destination pointer, just like strcat(). Then use that returned pointer directly in a printf() statement.

📖 Related Tutorials

  • 6. Concatenate Two Strings Using Pointers
  • 21. Copy One String to Another Using Pointers
  • 22. Compare Two Strings Using Pointers
  • 23. Calculate the Length of a String Using Pointers
  • 30. Swap Two Strings Using Pointers
  • All 30 Pointer Assignments

Previous Topic: -->> 19. Write a program in C language to implement a function to reverse a string using pointers.   ||   Next Topic: -->> 21. Write a program in C to implement a function to copy one string to another using pointers.


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.