Course contentsShow
← C
Lesson 482 of 1,2197. PointersFree lesson

Pointer-based `strcpy` implementation

Pointer-based strcpy implementation

What you'll learn: How to use pointer arithmetic to copy characters from one memory location to another using a concise, industry-standard C idiom.

The "Postman" approach to copying

In earlier lessons, you likely copied strings using array indexing, like dest[i] = src[i]. While that works, C programmers often use pointers to "walk" through memory.

Imagine two postmen standing side-by-side. The first postman (the source pointer) reads a letter at his current house, and the second postman (the destination pointer) writes that same letter down at his own house. After one letter is finished, they both take exactly one step forward to the next house. They keep doing this until the first postman sees a "Stop" sign (the null terminator \0).

The while loop magic

In C, we can combine the assignment, the step forward, and the stop condition into a single, elegant line of code. Because the assignment expression *dest = *src actually evaluates to the character being copied, the loop naturally ends when the null terminator (0) is reached.

void my_strcpy(char *dest, const char *src) {
    // While the character at src is copied to dest...
    // ...and that character is NOT the null terminator ('\0')
    while ((*dest = *src) != '\0') {
        dest++; // Move destination pointer to next byte
        src++;  // Move source pointer to next byte
    }
}

Why this works

  1. Dereferencing: *src looks at the actual character at the current memory address.
  2. Assignment: *dest = *src takes that character and saves it into the destination's address.
  3. Truthiness: In C, any non-zero value is "true." The loop continues as long as we are copying actual letters. When we finally copy the null terminator (\0), which has a numeric value of 0, the while condition becomes "false" and the loop stops.

This pointer-based approach is highly efficient because it avoids calculating the offset from the start of the array every time; it simply moves forward from where it currently stands.

Key takeaway

Pointer-based copying uses the null terminator as a natural stop signal while incrementing memory addresses to "walk" through a string.