C ++: does strcat () overwrite or move null?

Now consider this small program

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

Here, first, s has the value "One", and for visual presentation, this is s:

O - n - e - \ 0

Then I add “Two” to the end of the line, creating this:

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

Now that you see the only zero in the line first, after "One" now it is after "OneTwo"

My question is: Is NULL an overwritten string of "Two" and then adds its own zero at the end.

Or did the zero value that was already in the beginning return to the end again?

(This question may seem inappropriate, but I like to know about everything that I learn)

thanks

+6
source share
4 answers

The first \0 overwritten, and a new \0 added at the end of the concatenated string. There is no way to "move." These are locations to which values ​​are assigned.

+12
source

Although the question was answered correctly and repeatedly, it may be nice to get the most official answer from source ™. Or at least from sources that I can find on Google.

This document , which claims to be a C ++ standard (or its working draft), says:

The C ++ Standard Library provides 209 standard functions from the C library [including strcat]. - “Standard C Library”, C.2.7, p. 811

Turning to this document , declaring that it is International Standard C, we see:

The strcat function adds a copy of the line pointed to by s2 (including the terminating null character) to the end of the line indicated by s1 . The s2 character s2 overwrites the null character at the end of s1 . If copying occurs between objects, this overlap is undefined.

- " strcat Function", 7.21.3.1, p. 327

strcat really overwrites the null character.

+4
source

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

It does not move as such, the function simply adds \0 as the last character of the concatenated string.

+2
source

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

This is really nit-picking, but you will not be able to detect the difference in output no matter what method is used.

+2
source

Source: https://habr.com/ru/post/922241/


All Articles