string copy function

char a[201],*ptr,b[201];
for(i=0;i<strlen(a)-;i++) {
strncpy(b,&a[i],2);
puts(b);
}

this should copy the first 2 characters of a to the but it is displaying some garbage value after the second character of b.
input:
khitish
output:
kh&
hi&
it&
ti&
is&
sh&
can anybody tell me what is wrong??

Try to replace “char b[201];” with

char b[] = “xy Did you make sure to initialize array b[]?”;

( typo : strlen(a)- ==> strlen(a)-1 )

The reason for returned garbage is uninitialized array b. There might be possibilities that array b contains null at few positions and thus puts(b) prints the strings till that null char.

For better understanding try this program.

main()
{
	int i,c;
	char a[201],b[201];
	strcpy (a,"Kshitij");
	for(i=0;i<strlen(a)-1;i++) {
    	strncpy(b,&a[i],2);
    	c=puts(b);
	printf("c = %d\n", c);
	}
}

Here, puts returns number of characters written.

So better you initialize your array b[201].

Corrected code:


main()
{
	int i,c;
	char a[201],b[201]={};
	strcpy (a,"Kshitij");
	for(i=0;i<strlen(a)-1;i++) {
    	strncpy(b,&a[i],2);
    	c=puts(b);
		printf("c = %d\n", c);
	}
}

You will get better understanding from man pages.

You can use strncpy function function of string.h header file. After searching a little bit I got this c program to copy string. hope it helps.

//