C Program to copy one string to another string
Objective
Write a C program to copy one string into another string manually.
Algorithm / Approach
- Declare two character arrays:
a(source) andb(destination). - Read the source string.
- Use a
while(a[i] != '\0')loop to copy each character:b[i] = a[i]. - CRITICAL: After the loop terminates, explicitly add the null terminator to the destination string:
b[i] = '\0'. - Print the copied string.
main.c
#include<stdio.h>
int main( ) {
char a[100],b[100];
int i=0;
printf("Enter a String : ");
gets(a);
while(a[i] != '\0') {
b[i] = a[i];
i++;
}
b[i] = '\0';
printf("Copied String = : ");
i=0;
while(b[i] != '\0') {
printf("%c",b[i]);
i++ ;
}
return 0;
}
Expected Output
Enter a String : C Prowess Copied String = : C Prowess
Explanation of the Program
- Instead of using the built-in
strcpy()function fromstring.h, this program copies the data byte by byte. - Because we are copying character by character inside a loop, the loop stops right BEFORE the null terminator is copied. You MUST manually append the null terminator at the end of the destination array, otherwise printing it will result in trailing garbage data.
Complexity
Time Complexity
O(n)
Space Complexity
O(n)