I am working string copy program in c without using strcpy one variable to another without using the strcpy function. I understand that strcpy is the standard library function for this, but I want to implement it manually to understand how it works at a lower level.
My Approach
To copy a string manually, I plan to:
Use a loop to traverse the source string character by character.
Assign each character to the destination string.
Ensure that the copied string is null-terminated (\0).
Here’s a basic implementation I came up with:
c
Copy
Edit
#include <stdio.h>
void stringCopy(char *destination, const char source) {
while (source) { // Loop until the null character is reached
*destination = *source;
destination++;
source++;
}
*destination = '\0'; // Null-terminate the copied string
}
int main() {
char source[] = "Hello, World!";
char destination[50]; // Ensure the destination array has enough space
stringCopy(destination, source);
printf("Copied String: %s\n", destination);
return 0;
}
Explanation
The function stringCopy takes two pointers: destination (where we copy the string) and source (the string to be copied).
The while loop iterates through the source string and assigns each character to the destination.
Once the loop ends, we manually add the null terminator (\0) to mark the end of the copied string.
In main(), we define a source string and a destination array, then call stringCopy().
Alternative Approaches
Apart from using a pointer-based approach, we can also implement it using array indices:
c
Copy
Edit
#include <stdio.h>
void stringCopy(char destination[], const char source[]) {
int i = 0;
while (source != '\0') {
destination = source;
i++;
}
destination = '\0'; // Null-terminate the string
}
int main() {
char source[] = "C Programming";
char destination[50];
stringCopy(destination, source);
printf("Copied String: %s\n", destination);
return 0;
}
This method works similarly but uses an index variable (i) instead of pointer arithmetic.
Questions & Discussion
Are there any performance advantages of using pointers over array indices?
How can we modify this function to handle edge cases like NULL pointers or empty strings?
Would using memcpy be a more efficient alternative in some cases?