I have learned that the work of strcpy
is to copy the content of one string into another. Till now I was thinking that when we use strcpy
then the old content is totally deleted and the new contained is copied. Kindly see the following program:
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char str[]="abcdef";
strcpy(str,"xyz");
cout<<str[4];
cout<<str;
return 0;
}
The output is exyz
. Please visit this online compiler to see the compiled code.
My first problem is that, that when a new string is copied then the old contained must be deleted but this is not happening here.
Then I concluded that since the new string length is smaller than the existing one therefore only first three contained are deleted and rest are left.
But when I have written cout<<str[3];
then nothing happened.
Why on cout<<str[4];
we are getting e
but on cout<<str[3];
we are not getting d
.