1

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.

Singh
  • 229
  • 2
  • 3
  • 7
  • "xyz" has a \0 at the end of it, thats why you dont see d but you see e. Its also why you should be using std::string and not C-strings. – Borgleader Dec 09 '14 at 14:09

1 Answers1

2

'd' is overwritten by the null terminator, so str[3] is just a zero. str[4] then contains 'e'. strcpy() only modifies as many characters as it needs to, and it has no idea how long str is, so it cannot zero out the rest.

If you want to truly zero out the array, then use a memset() on it.

whoan
  • 8,143
  • 4
  • 39
  • 48
JHumphrey
  • 958
  • 10
  • 15
  • Sir, but when we are doing `cout< – Singh Dec 09 '14 at 16:41
  • 1
    @Singh: `cout << str` shows only the characters prior to the first `\0` in `str[]`. You put `\0` in `str[3]` – MSalters Dec 09 '14 at 16:44
  • After the strcpy, the array `str` contains `{'x', 'y', 'z', 0, 'e', 'f', 0}`. Note that the zeros are null terminators. As the others noted, printing halts at the first null terminator. – JHumphrey Dec 09 '14 at 20:05