I want to copy the last four characters in one character array to another array. I tried doing it like I have shown below.
{
char date[20],day[2],year[4];
int n,i,j;
gets(date);
n=strlen(date);
j=n-1;
for(i=3;i>=0;i--)
{
year[i]=date[j];
j--;
}
printf("%s",year);
}
but when I copied it, even though the second array is small, it copies the entire string and also the four characters.
For example if the input was 16 july 1776
the output is year=177616 july 1776
What is the cause and solution to this?
iorjorn. It usesgets()— see Whygets()is too dangerous to be used. You've not allowed enough space for 4 digits for the year and a null terminator byte, nor have you added a null terminator byte. That's likely the cause of your trouble. Similarly with thedayarray, though you don't show that being set.printfcontinued reading until it finally came across the null byte inserted bygets(). So, it was good luck that your mistakes were easily spotted. But you were invoking undefined behaviour which is unconditionally a Bad Idea!