strcpy( ) in C

This function copies the contents of one string into another. The base addresses of the source and target strings should be supplied to this function. Here is an example of strcpy( )

#include <stdio.h>

int main() {

	char source[] = "Humpty ";
	char target[20] = "";
	strcpy(target, source);
	printf("\nsource string = %s", source);
	printf("\ntarget string = %s", target);
	getchar();
	return 0;
}

On supplying the base addresses, strcpy( ) goes on copying the characters in source string into the target string till it doesn’t encounter the end of source string (‘\0’). It is our responsibility to see to it that the target string’s dimension is big enough to hold the string being copied into it. Thus, a string gets copied into another, piece-meal, character by character. There is no short cut for this. Let us now attempt to mimic strcpy( ), via our own string copy function, which we will call xstrcpy( ).

#include <stdio.h>

int main() {

	char source[] = "Humpty ";
	char target[20] = "";
	xstrcpy(target, source);
	printf("\nsource string = %s", source);
	printf("\ntarget string = %s", target);
	getchar();
	return 0;
}
xstrcpy(char *t, char *s) {
	while (*s != '\0') {
		*t = *s;
		s++;
		t++;
	}
	*t = '\0';
}