Problem of string in C lang.

its a program to copy a string in another string.the program is running properly but it is giving a wrong output for special characters. can u help me.???

#include<stdio.h>
#include<conio.h>
void main(){
char s1[20],s2[20];
int i=0;  
printf("enter your name \n");
gets(s1);
gets(s2);
while(s2[i]!='\0')
{
   s1[i]=s2[i];
   i++;
}
printf("copied name in s1 is ");
puts(s1);
getch();

}

in output window
s1=hello
s2=!@#%^&*() ans.in s1 shud be !@#%^&()
but it is !@#%^&*()@ or !@#%^&
()a

2 Likes

The problem is that the first character string which you created is of length less than the character string which you created second. So the character ‘\0’ which marks the termination of the string is overwritten in the case when you try to write the second string to the first. And hence when you try to print the whole of the first string it would take few extra characters from the end uptill it finds ‘\0’ hence takes some garbage characters.

4 Likes

Any time if you update of create a string without using inbuilt functions.You should always care about the termination character of the string that is ‘\0’ .If you will not append a ‘\0’ then the string would not be accessible properly.

I thing you should check this…


and that is the problem with string terminator .