C Program to Copy String Without strcpy Function
strcpy by using a loop to copy each character until the null terminator is reached, like while(src[i] != '\0') { dest[i] = src[i]; i++; } dest[i] = '\0';.Examples
How to Think About It
strcpy, think of copying each character one by one from the source string to the destination string until you reach the end, which is marked by the null character \0. This way, you manually replicate what strcpy does internally.Algorithm
Code
#include <stdio.h> int main() { char src[] = "Hello, World!"; char dest[50]; int i = 0; while (src[i] != '\0') { dest[i] = src[i]; i++; } dest[i] = '\0'; printf("Copied string: %s\n", dest); return 0; }
Dry Run
Let's trace copying "Hi" from src to dest through the code.
Initialize variables
src = "Hi", dest = uninitialized, i = 0
Copy first character
dest[0] = src[0] = 'H', i = 1
Copy second character
dest[1] = src[1] = 'i', i = 2
Copy null terminator
dest[2] = src[2] = '\0', loop ends
Result
dest = "Hi"
| i | src[i] | dest[i] |
|---|---|---|
| 0 | H | H |
| 1 | i | i |
| 2 | \0 | \0 |
Why This Works
Step 1: Copy characters one by one
The loop copies each character from source to destination until it finds the null character \0, which marks the string's end.
Step 2: Stop at null terminator
When the null character is copied, the loop stops to avoid copying extra memory.
Step 3: Add null terminator to destination
The destination string is properly ended with \0 so it behaves like a valid C string.
Alternative Approaches
#include <stdio.h> int main() { char src[] = "Hello"; char dest[50]; char *pSrc = src, *pDest = dest; while (*pSrc != '\0') { *pDest = *pSrc; pSrc++; pDest++; } *pDest = '\0'; printf("Copied string: %s\n", dest); return 0; }
#include <stdio.h> int main() { char src[] = "Test"; char dest[50]; int i = 0; do { dest[i] = src[i]; } while (src[i++] != '\0'); printf("Copied string: %s\n", dest); return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs once for each character in the source string until the null terminator, so it is linear in the length of the string.
Space Complexity
No extra space besides the destination array is used; copying is done in-place character by character.
Which Approach is Fastest?
Pointer-based copying can be slightly faster due to direct memory access, but both loop and pointer methods are efficient for typical string sizes.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Index loop | O(n) | O(1) | Simple and clear copying |
| Pointer increment | O(n) | O(1) | Efficient and idiomatic C |
| Do-while loop | O(n) | O(1) | Copying including empty strings |
\0 at the end of the destination string to avoid undefined behavior.\0 at the end of the copied string causes errors when printing or using the string.