void xstrcpy ( char *t, char *s );
void main(void ) {
char source[ ] = "Sayonara" ;
char target[20] ;
xstrcpy ( target, source ) ;
printf ( "\nsource string = %s", source);
printf ( "\ntarget string = %s", target ) ;
}
void xstrcpy ( char *t, char *s ) {
while ( *s != '\0' ){
*t = *s ;
t++ ; s++ ;
}
*t = '\0' ;
}
this code gives output:
source string = Sayonara
target string = Sayonara
But when I change char target[20]; to char target[8];, it gives:
source string = target string = Sayonara
When I change char target[20]; to char target[4];, it gives:
source string = nara
target string = Sayonara
When I change char target[20]; to char target[3];, it gives:
source string = nara
target string = Sayonara
Why does the source value change, and target becomes array having size of string?
When your target is shorter than required, it overwrites whatever data following it. In particular, when you make it
8, it overwrites with terminating zero the beginning of the source. When you make it4, it overwrites source with the tail of the source string.This is what’s happening. Though this behaviour is not guaranteed, of course, being undefined.