In c program to copy a string without using strcpy function to copy one string into another. However, there are situations where we might need to implement this functionality manually without using strcpy. In this post, we will discuss how to copy a string without using the built-in strcpy function and provide a simple C program to achieve this.
Why Avoid strcpy?
There are several reasons why you might want to avoid strcpy:
Understanding String Manipulation – Manually copying a string helps in understanding pointers and loops.
Avoiding Buffer Overflows – strcpy does not perform bounds checking, which may lead to buffer overflows.
Custom Implementation – You may need a custom function for additional functionality, such as checking length or handling special characters.
C Program to Copy a String Manually
Below is a simple C program that copies a string from source to destination without using the strcpy function:
c
Copy
Edit
#include <stdio.h>
void copyString(char *source, char *destination) {
int i = 0;
// Copy each character from source to destination
while (source[i] != '\0') {
destination[i] = source[i];
i++;
}
// Add null terminator at the end
destination[i] = '\0';
}
int main() {
char source[] = "Hello, World!";
char destination[50]; // Ensure sufficient space for the copied string
// Call the function to copy the string
copyString(source, destination);
// Display the copied string
printf("Source String: %s\n", source);
printf("Copied String: %s\n", destination);
return 0;
}
Explanation of the Code
Function Definition (copyString):
A loop iterates through the source string.
Each character is copied to destination.
The loop stops when it reaches the null character (\0).
Finally, a null character is manually added to destination to terminate the string.
Main Function (main):
Declares a source string.
Creates a destination array with enough space.
Calls copyString to copy the string.
Prints both source and destination to verify the result.
Alternative Method Using Pointers
Another way to implement this is by using pointers instead of array indexing:
c
Copy
Edit
#include <stdio.h>
void copyString(char *source, char destination) {
while (source) {
*destination = *source;
source++;
destination++;
}
*destination = '\0';
}
int main() {
char source[] = "C Programming";
char destination[50];
copyString(source, destination);
printf("Copied String: %s\n", destination);
return 0;
}
Key Takeaways
We manually copied a string without using strcpy.
Two approaches were demonstrated: one using array indexing and another using pointers.
The implementation ensures the string is properly null-terminated.