Question

Now lets see this small program

char s[20]="One";
strcat(s,"Two");
cout<<s<<endl;

Here at first s has the value "One" and for visual representation this is the value of s:

O - n - e - \0

Then I add "Two" to the end of the string producing this:

O - n - e - T - w - o - \0

Now as you can see the only null in the string at first was after "One" now it is after "OneTwo"

My question is: Is the null overwritten by the string "Two" and then it adds it's own null at the end.

Or is the null that was already there in the beginning moved back to be at the end again?

(This question might seem not to make a difference but I like to know about everything I learn)

Thank you

Was it helpful?

Solution

The first \0 is overwritten, and a new \0 is added at the end of the concatenated string. There is no scope for "moving" anything here. These are locations to which values get assigned.

OTHER TIPS

Although the question has been answered correctly and repeatedly, it may be nice to get a most officialest answer from the source™. Or at least from the sources I can find with Google.

This document, which claims to be the C++ Standard (or a working draft thereof), says:

The C++ Standard library provides 209 standard functions from the C library [including strcat]. --"Standard C library", C.2.7, pg 811

Jumping over to this document claiming to be the C International Standard, we see:

The strcat function appends a copy of the string pointed to by s2 (including the terminating null character) to the end of the string pointed to by s1. The initial character of s2 overwrites the null character at the end of s1. If copying takes place between objects that overlap, the behavior is undefined.

--"The strcat function", 7.21.3.1, pg 327

strcat does indeed overwrite the null character.

Yes, the \0 of the first argument to strcat gets overwritten, and it becomes the last character of the concatenated string.

It doesn't move as such, the function just appends \0 as the last character of the concatenated string.

The only way to know for sure is to look at the source of your particular version of strcat. The typical implementation will overwrite the first null and copy the null from the second string into the last position.

This is really nit-picking though, you won't be able to detect the difference in the output no matter which method is used.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top