Alex Rivera | Logout

C++: strcpy Function copies null?

Asked 2012-08-06T15:10:38.057
33

While using string manipulation functions specificaly strcpy I did this small program.

char s1[8]="Hellopo";
char s2[4]="sup";
strcpy(s1,s2);
cout<<s1<<endl;

When I printed out s1 It actually just printed out "sup". I expected it to print "suplopo".

Then I did this:

cout<<s1+4 << endl;

It printed out "opo";

And The output of this: cout<<s1+3<<endl; was nothing

So after thinking a bit about it.

I came to this conclusion. Since C++ stops outputing the string once it reaches the null terminator. Therefore the null must have been copied in the strcpy function. Resulting in this string:

s - u - p - \0 - o - p - o -\0;

Please tell me if this is correct or not. And if im not please correct me.

And if you have any more info to provide please do.

Edit
Report

1 Answer

2

You are correct. For the effect you initially expected, you would use strncopy. strncopy copies the null terminator as long as you specify the correct length of the string that is being copied.

answered 2012-08-06T15:15:29.313

Your Answer