strcpy() copies a null-terminated source string, including its terminating \0, into a destination array. The destination must have enough space for the complete source string.
strcpy(destination, source);
#include <stdio.h>
#include <string.h>
int main(void) {
char source[] = "My First Name";
char destination[30];
strcpy(destination, source);
printf("%s\n", destination);
return 0;
}
#include <stdio.h>
int main(void) {
char source[] = "welcome to c program";
char destination[100];
size_t i = 0;
while (source[i] != '\0') {
destination[i] = source[i];
i++;
}
destination[i] = '\0';
printf("%s\n", destination);
return 0;
}
#include <stdio.h>
#include <string.h>
int main(void) {
char source[100];
char destination[100];
printf("Enter a string: ");
if (fgets(source, sizeof(source), stdin) == NULL) {
return 1;
}
strcpy(destination, source);
printf("Copied string: %s", destination);
return 0;
}
strcpy() does not know the size of the destination array. Copying a source string that is too large causes undefined behavior. Use an adequately sized destination and validate input lengths when the source size is not controlled.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.