Pointer Assignment 8 — Copy One String to Another Using Pointers
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Copy One String to Another Using Pointers — Two Pointers, One Character at a Time

📑 On this page:
  • How String Copy Works in Memory
  • The Two Steps of Strcpy
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to copy characters with two parallel pointers
  • Why the null terminator must also be copied
  • Why the destination array must be large enough
  • The classic *dest++ = *src++ idiom
  • Why comparing pointers is not the same as comparing strings

How String Copy Works in Memory

Copying a string means copying every character — one by one — from the source buffer to the destination buffer, until and including the null terminator '\0'. The source string stays exactly as it is; only the destination changes. The two strings are independent after the copy: modifying one does not affect the other (unlike assigning one pointer to another).

In C, strings are arrays of characters ending in '\0'. There is no built-in "copy the array" operation for them, so strcpy does the job manually — or, as in this exercise, with pointers. Two pointers advance together: src reads from the source, dest writes to the destination. On each iteration the current source character is written to the destination, and both pointers move forward. When *src is the terminator, we stop — but we still write that terminator to the destination, otherwise the copied string wouldn't be valid.

The critical precondition: the destination must have room. The destination array needs at least strlen(src) + 1 bytes — one for each character and one for the terminator. If the destination is too small, the copy writes past the end of the array, corrupting adjacent memory. That's undefined behaviour and one of the most common bugs in C code. The pointer-based approach makes the copy explicit, so the buffer-size contract is visible right in the loop.

💡 In one line: Copy = walk src and dest together, assign one character per step, and don't forget to copy the '\0'.

Diagram showing two pointers walking in parallel while copying characters from a source string to a destination string in memory, including the null terminator

The Two Steps of Strcpy

Step Pointer operation Effect
1. Copy the characterswhile (*src) *dest++ = *src++;All source characters except the terminator are copied
2. Terminate*dest = '\0';The destination becomes a valid C string

Step 1 uses the compact idiom *dest++ = *src++. Unpacked: take the character that src points at, write it where dest points, then advance both pointers. The post-increment returns the original value, so the write happens first, then both pointers move. The check *src before the assignment stops the loop when the source's terminator is reached — the terminator is not copied inside the loop, which is why step 2 is needed. Some implementations instead write a loop that copies the terminator too:

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

This assigns, advances both pointers, then compares the assigned character to '\0'. The loop exits when the terminator has been copied — so the destination is complete and step 2 becomes unnecessary. Both forms are correct; the explicit two-step version is easier to follow for beginners, while the one-liner is the classic strcpy idiom and is very common in real code.

Complete C Program

Program: copy one string to another using parallel pointer walks (implementation of strcpy)

#include <stdio.h>

/* Copy src into dest. dest must have room for src + '\0'. */
void str_copy(char *dest, const char *src) {
    if (dest == NULL || src == NULL) {
        return;
    }

    /* Step 1: copy characters one at a time */
    while (*src != '\0') {
        *dest = *src;
        dest++;
        src++;
    }

    /* Step 2: terminate the result */
    *dest = '\0';
}

int main(void) {
    /* dest must be large enough for src plus '\0' */
    char dest[50];
    const char *src = "Hello, World!";

    /* Initialize dest to something recognizable so we can see the change */
    dest[0] = '-';
    dest[1] = '\0';

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

    str_copy(dest, src);

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

    return 0;
}
                                    

Program Output

Before copy:
  src  = "Hello, World!"
  dest = "-"

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

After the call, dest contains the same characters as src — thirteen characters plus the terminator. The source is untouched: its bytes were read but never written. The destination started as a one-character string "-", but since the copy writes over the buffer from the beginning, the old content is completely replaced. If the destination had contained a longer string, the copy would still work correctly — the terminator in the copied data marks where the new string ends, and any old bytes after that are simply unused.

Step-by-Step Explanation

Let's trace the pointers through memory.

1. Setup

src points at the string literal "Hello, World!" — fourteen bytes: thirteen characters plus '\0'. dest is a 50-byte array on the stack. It currently holds '-' followed by '\0', and the remaining 48 bytes are uninitialized (which is fine — we're about to overwrite the beginning). The destination is large enough for this source, so the copy is safe.

2. The copy loop

The loop condition *src != '\0' checks whether the current source character is the terminator. If not, the body runs: *dest = *src writes the character, then dest++ and src++ advance both pointers. After each iteration the destination contains one more copied character and the source pointer has moved one step forward.

3. Tracing the iterations

  • Iteration 1: *src = 'H' → *dest = 'H', both advance. dest[0] is now 'H'.
  • Iteration 2: *src = 'e' → *dest = 'e', both advance. dest[1] is now 'e'.
  • Iteration 3: *src = 'l' → *dest = 'l', both advance. dest[2] is now 'l'.
  • … and so on through 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!'.
  • Iteration 14: *src = '\0'. The loop condition fails, so the body does not run. The terminator has not been copied.

4. Step 2 — terminate

After the loop, dest points one byte past the last copied character — exactly where the terminator needs to go. The statement *dest = '\0' writes it. Now dest holds 'H','e','l','l','o',',',' ','W','o','r','l','d','!','\0' — a valid C string of length 13, identical to the source.

5. What if dest weren't large enough?

Suppose dest had only 10 bytes. The loop would copy the first 10 characters, then continue writing past the end of the array — into whatever memory follows on the stack. This corrupts that memory, which could be another local variable, saved registers, or a return address. The behaviour is undefined: the program might crash, might silently produce wrong results later, or might appear to work and fail mysteriously elsewhere. Ensuring dest is at least strlen(src) + 1 bytes is the caller's responsibility, and forgetting it is the classic string-copy bug.

6. Why not just dest = src?

Because that copies the pointer, not the string. If dest is a pointer variable, dest = src makes both point to the same memory. Then modifying one would appear to modify the other, since there's only one underlying buffer. If dest is an array (like ours), the assignment is actually illegal — arrays can't be assigned in C. The manual loop copies the contents, creating two independent strings.

7. Why const char *src?

The source is read but never written, so marking it const documents that promise. It also lets callers pass string literals — like "Hello, World!" — without warnings. The destination must be non-const, since we're writing to it. This is the same signature convention as standard strcpy.

8. Why does dest start with '-'?

Purely for demonstration. Printing the destination before and after the copy shows the change clearly — the old content is replaced by the new string. In a real program the destination's previous content doesn't matter, since the copy overwrites it from the beginning. The only requirement is that the destination buffer is big enough; its old contents are irrelevant.

9. Can I use the one-line idiom instead?

Yes. The form while ((*dest++ = *src++) != '\0') ; is the classic strcpy loop. It copies the terminator as part of the copy, so no separate termination step is needed. It's compact and idiomatic, and many experienced C programmers prefer it. The explicit two-step version (copy characters, then terminate) is easier to read for beginners and easier to audit when reviewing code. Both are correct; the choice is stylistic.

10. Is the source really unchanged?

Yes. We only read *src, never assigned to it. The src pointer itself advances inside the function, but it's a local copy of the caller's pointer — advancing it doesn't affect the caller's variable. The bytes in the source buffer are untouched. The output line src = "Hello, World!" (unchanged) confirms this.

11. What's the difference between this and memcpy?

memcpy copies a fixed number of bytes and doesn't stop at a null terminator. It's used when you know the length, or when the data isn't a C string at all (binary data, for example). strcpy and this function stop at the first terminator and copy it, making them suitable for null-terminated strings. If you have a buffer that isn't null-terminated but you know its length, use memcpy. If it's a proper C string, either works — but strcpy expresses the intent more clearly.

12. How do I avoid buffer overflow?

The safest approach is to know the destination's size and verify it against the source length before copying. In C, strncpy or snprintf are bounded alternatives — though strncpy has its own quirks (it may not terminate the destination if the buffer is exactly full). A common safe pattern is to compute len = strlen(src), check len + 1 <= dest_size, and then copy manually or with memcpy. The pointer loop in this program is the foundation; bounded versions are small variations on it.

🎯 Remember this: Copy has two mandatory steps — copy the characters, then write the terminator. Skip the terminator and the destination isn't a valid string. And always verify the destination has space for the full source, including the terminator.

Frequently Asked Questions

1. Why not just use strcpy?

In production code, strcpy is standard, portable, and likely optimized. This exercise teaches you how it works so that you can write bounded variants (strncpy with proper termination, or memcpy with a known length), copy substrings, or handle special cases like truncation. It's also a common interview question and a useful foundation for more complex string operations.

2. How much space do I need in dest?

At least strlen(src) + 1 bytes — one for each character and one for the terminator. If you're copying into an array declared as char dest[N], verify that N >= strlen(src) + 1. If the source is user-provided or of unknown length, compute the length first, allocate enough space (possibly with malloc), then copy. Never copy into a fixed-size buffer without checking.

3. What if the strings overlap?

This function is undefined if the source and destination overlap in memory — the same restriction as standard strcpy. If you need overlap-safe copying, use memmove, which handles overlapping regions correctly by choosing the copy direction based on the relative addresses. For non-overlapping strings, the simple forward copy in this program is fine.

4. What does the function return?

In this version, nothing. The destination array is modified in place, and the caller already has its address. Standard strcpy returns dest for chained expressions like printf("%s", strcpy(a, b)), but that's optional. Many C library functions return their destination for exactly this convenience, though it's rarely used in practice.

5. Is the null terminator always copied?

In this implementation, yes — but in two steps. The copy loop stops before copying the terminator; then the explicit *dest = '\0' writes it. The result is a correctly terminated destination. If you use the compact while ((*dest++ = *src++) != '\0') form, the terminator is copied as part of the loop condition's final evaluation. Either way, the terminator ends up at the right place.

6. What if either pointer is NULL?

Dereferencing NULL is undefined behaviour. The function guards against it: if (dest == NULL || src == NULL) return;. This is defensive programming — a correct caller never passes NULL, but a reusable function benefits from checking. In production, some argue that it's better to let the crash happen loudly, since a NULL source pointer is a caller bug that should be fixed, not silently ignored. Which approach is better depends on the context.

💡 Tip: After this works, try implementing a bounded version: str_copy_n(char *dest, size_t dest_size, const char *src). Track how many characters you've written, stop before overflowing, and always write the terminator (even if you had to truncate). This is the safe, production-grade version — it never overflows no matter what input the caller provides.

📖 Related Tutorials

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

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