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

C Program: Concatenate Two Strings Using Pointers — Walking to the End, Then Copying

📑 On this page:
  • How Concatenation Works in Memory
  • The Three Steps of Strcat
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to walk a pointer to the end of the first string with a single while loop
  • Why concatenation is really "copy starting at the destination's null terminator"
  • How to copy the source string character by character using pointer increments
  • Why you must write a null terminator after the copy
  • The classic buffer-overflow trap that arises when the destination is too small

How Concatenation Works in Memory

Concatenation means "join two strings end to end." In memory, this is a two-step process. First, you find the end of the first string — that is, the position of its null terminator. Second, you start copying the second string at that position, byte by byte, overwriting the terminator and continuing until you reach the source's own terminator. Finally, you must write a new terminator after the last copied character.

The second string is not modified. Its bytes are copied to the end of the first string's buffer. This means the first string's buffer must be large enough to hold both strings plus one extra byte for the terminator. If the destination array isn't big enough, the copy silently writes past the end of the array, corrupting adjacent memory — the classic buffer overflow. This program's correctness depends entirely on the caller reserving enough space.

The pointer-only approach makes each of these steps visible. You don't need strlen or indices — just two pointers, a while to reach the end, another while to copy, and a single assignment to terminate.

💡 In one line: Concatenation = walk to the first string's terminator, copy the second string there, write a new terminator. The buffer must be big enough for all three.

Diagram showing two strings being concatenated in memory, with a pointer walking to the first string's null terminator and then copying the second string's characters into that position

The Three Steps of Strcat

Step Pointer operation Effect
1. Find the endwhile (*p) p++;p now points at the destination's '\0'
2. Copy the sourcewhile (*src) *p++ = *src++;Characters are copied one at a time
3. Terminate*p = '\0';The concatenated string is a valid C string

Step 2 uses the very common idiom *p++ = *src++. Unpacked, it means: read the character that src points at, write it to the location p points at, then advance both pointers. The post-increment returns the original value, so the assignment happens at the current position before either pointer moves. It's concise but readable once you've seen it; many C programmers write it exactly this way. The check *src before the assignment means we stop when the source's terminator is reached — we've copied everything we need to. Then step 3 writes the terminator at the current position of p, completing the string.

Complete C Program

Program: concatenate two strings using pointer walks (implementation of strcat)

#include <stdio.h>

/* Concatenate src onto the end of dest. dest must have room. */
void str_concat(char *dest, const char *src) {
    if (dest == NULL || src == NULL) {
        return;
    }

    /* Step 1: walk p to the end of dest */
    char *p = dest;
    while (*p != '\0') {
        p++;
    }

    /* Step 2: copy src's characters, one at a time */
    while (*src != '\0') {
        *p = *src;
        p++;
        src++;
    }

    /* Step 3: terminate the result */
    *p = '\0';
}

int main(void) {
    /* dest must be large enough for dest_len + src_len + 1 */
    char dest[50] = "Hello, ";
    const char *src = "World!";

    printf("Before concat:\n");
    printf("  dest = \"%s\"\n", dest);
    printf("  src  = \"%s\"\n", src);

    str_concat(dest, src);

    printf("\nAfter concat:\n");
    printf("  dest = \"%s\"\n", dest);
    printf("  src  = \"%s\"  (unchanged)\n", src);

    return 0;
}
                                    

Program Output

Before concat:
  dest = "Hello, "
  src  = "World!"

After concat:
  dest = "Hello, World!"
  src  = "World!"  (unchanged)
                                

The destination now holds the two strings joined — "Hello, World!" — thirteen characters plus the terminator. The source is untouched: its bytes were read but not modified. Note that the original destination had a space after the comma, so the result reads naturally. If it had been just "Hello" with no trailing space, the concatenation would have produced "HelloWorld!" — concatenation doesn't insert separators; it just glues the bytes together.

Step-by-Step Explanation

Let's trace the pointers through memory.

1. Setup

dest is a 50-byte array containing 'H','e','l','l','o',',',' ','\0' followed by unused bytes. src points at the literal "World!" — seven bytes: 'W','o','r','l','d','!','\0'. The destination has 50 bytes but only 8 are currently meaningful (7 letters plus the terminator).

2. char *p = dest;

A local pointer p starts at the beginning of the destination. We'll use p as the write cursor. We must not lose track of dest's original address, so we don't advance dest itself — we advance p, which is a copy.

3. Step 1 — walk p to the end

The loop while (*p != '\0') p++; steps p forward one byte at a time. It examines 'H', advances; examines 'e', advances; ... eventually examines the space, advances, and now *p is '\0'. Loop exits. p points at the destination's terminator — the position where we should start writing.

4. Step 2 — copy the source

The loop while (*src != '\0') { *p = *src; p++; src++; } copies one character at a time. Iteration 1: *src is 'W', so *p = 'W' overwrites the destination's terminator; advance both pointers. Iteration 2: 'o' copied, advance. ... Iteration 6: '!' copied, advance. Now *src is '\0', condition false, loop exits. We've copied all six characters of "World!".

5. Step 3 — terminate

After the copy loop, p points one byte past the last copied character. We write *p = '\0'. The destination array now contains 'H','e','l','l','o',',',' ','W','o','r','l','d','!','\0' — a valid C string of length 13. Without this step, the array would contain the copied characters but no terminator, and any subsequent printf("%s") would keep reading past '!' into whatever memory came next. That's the single most common strcat bug.

6. What if dest weren't large enough?

Suppose we declared char dest[8] and tried to append "World!". The first six bytes of dest hold "Hello, " plus the terminator; the copy loop would write six more bytes starting at position 7 — positions 7 through 12. But the array only has valid slots 0 through 7. Bytes at positions 8 through 12 belong to whatever else is on the stack — possibly another local variable, possibly padding, possibly a return address. Writing there corrupts that data. This is undefined behaviour: sometimes a crash, sometimes silent corruption of nearby variables, occasionally a mysterious "random" value showing up somewhere else. Always ensure the destination has room.

7. Why const char *src?

The function reads from src but never writes through it, so marking it const documents that promise and lets the compiler catch accidental writes. It also allows callers to pass string literals (which live in read-only memory) without warnings. The destination must be non-const, since we're writing to it.

8. Why void return type?

Because the destination array is modified in place. The caller already has the address of dest — returning it would be redundant. Standard strcat returns dest for convenience in chained expressions like printf("%s", strcat(a, b)), but that's optional. For a beginner example, void keeps the function's intent clean: "I modify dest; that's my entire job."

9. Can I write this without an explicit '\0' check?

You can compress step 2 into a single expression:

while ((*p++ = *src++) != '\0')
    ;
                                

This assigns, advances both pointers, then compares the assigned character to '\0'. The loop exits when the terminator has been copied — and conveniently, the terminator is written, so step 3 becomes unnecessary. This is the classic "strcpy idiom" and it's very terse. It's also a bit dense for beginners; the explicit three-step version is easier to reason about and audit for correctness. Both are correct; pick the one your team reads more easily.

10. Is the source really unchanged?

Yes. We only read *src, never assigned to it. The src pointer itself advances inside the function (to walk through the string), but src is a local copy of the caller's pointer — advancing it has no effect on the caller's variable. Both the caller's pointer and the underlying bytes it points to remain exactly as they were. The output line src = "World!" (unchanged) confirms this.

🎯 Remember this: Concatenation has three mandatory steps — walk to the end, copy the source, write the terminator. Skip any of them and you get either a truncated string or a memory bug. And always verify the destination has space for both strings plus one extra byte.

Frequently Asked Questions

1. Why not just use strcat?

In production code, strcat and its safer cousin strncat are the standard choices — tested, portable, likely optimized. This exercise teaches you how they work so that when you need a variant (e.g., concatenating only the first k characters, or appending to a string of unknown length in a bounded buffer), you can write it confidently. It's also common in interviews and in code-review situations to demonstrate this understanding.

2. How much space do I need in dest?

strlen(dest) + strlen(src) + 1 bytes. The "1" is for the terminating null. If you allocate exactly that much, you're safe. If you allocate less, you have a buffer overflow. If you allocate more, the extra bytes are unused (unless you later append more). A common safe pattern when the strings are user-provided is to compute the combined length first, then allocate with malloc or, if it's on the stack, verify the destination array is large enough before calling strcat.

3. Can I concatenate a string onto itself?

Not with this naive implementation. If dest == src, then the pointer walks and copies overlap in a way that produces undefined behaviour — the copy loop may overwrite parts of the source before they're read. Standard strcat also forbids self-append. If you need it, allocate a temporary buffer, build the result there, then copy back. Or use strncat with a bound you've carefully checked — but the safest rule is: never append a string to itself with the plain functions.

4. What if the destination has extra capacity after the first string?

That's fine — the extra capacity is exactly the room we're using for the append. The first loop stops at the terminator, which is inside the buffer if the string is shorter than its buffer. The copy proceeds from there. The terminator is a marker, not the physical end of the buffer. Buffers typically have slack; the string length is what matters.

5. What does the function return?

In this version, nothing. The destination array is modified in place, and the caller already has its address. If you want chained calls like printf("%s", str_concat(a, b)), change the return type to char * and return dest; at the end — that's what standard strcat does. Many C functions return their destination for exactly this pattern.

6. What if either pointer is NULL?

Dereferencing NULL is undefined behaviour — usually a segfault. The function guards against it: if (dest == NULL || src == NULL) return;. This is defensive; a correctly written caller shouldn't pass NULL. But since this function is intended as a building block, protecting the entry point is a small cost for a much clearer failure mode (silent no-op) than a crash deep in a copy loop.

💡 Tip: After this works, try the bounded variant: str_concat_n(char *dest, size_t dest_size, const char *src). Track the current length, refuse to append more than dest_size - current_len - 1 characters, and always terminate. This is the safe, production-grade version — it never overflows regardless of the caller's input, which makes it a great stepping stone to serious string handling.

📖 Related Tutorials

  • 5. Length of a String Using Pointers
  • 7. Compare Two Strings Using Pointers
  • 8. Copy One String to Another Using Pointers
  • 20. Concatenate Two Strings — Function Version
  • 21. Copy One String to Another — Function Version
  • All 30 Pointer Assignments

Previous Topic: -->> 5. Length of a String Using Pointers   ||   Next Topic: -->> 7. Compare Two Strings 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.