I’m currently working on a string copy in c without using strcpy from one variable to another without using the strcpy function. I know strcpy is the standard way to do this, but I want to understand how to implement it manually, either for learning purposes or when certain libraries aren’t available.
From what I understand, a string in C is basically a character array ending with a null character (\0). So, to copy one string to another, we need to loop through each character of the source string and assign it to the destination string until we hit the null terminator.
Here’s a simple implementation of string copying without strcpy:
c
Copy
Edit
#include <stdio.h>
void stringCopy(char *dest, const char src) {
while (src) { // Loop until null terminator is reached
*dest = *src;
dest++;
src++;
}
*dest = '\0'; // Add null terminator at the end
}
int main() {
char source[] = "Hello, World!";
char destination[50]; // Make sure it's large enough
stringCopy(destination, source);
printf("Copied String: %s\n", destination);
return 0;
}
Explanation:
The function takes two pointers: dest (destination string) and src (source string).
A while loop iterates over src and assigns each character to dest.
When the null terminator (\0) is encountered, it’s also copied to dest, ensuring the copied string is properly terminated.
In main(), we declare a source string and a sufficiently large destination array.
The function is called, and the copied string is printed.
This method works similarly to strcpy but does not use the built-in function. However, it’s important to ensure the destination array is large enough to hold the copied string, otherwise, it may cause a buffer overflow.
Alternative Approaches:
Using Pointer Arithmetic:
Instead of indexing, we can use pointer incrementing:
c
Copy
Edit
void stringCopy(char *dest, const char src) {
while ((dest++ = *src++)); // Copies and checks for '\0' in one step
}
Using a for Loop:
c
Copy
Edit
void stringCopy(char *dest, const char *src) {
for (; *src != '\0'; src++, dest++) {
*dest = *src;
}
*dest = '\0';