String construct got space for the data by doing
new char[strlen(cp)+1];
Since there are only strlen(cp)characters in the string, what is the extra byte for?
For the special '\0' char which indicates end of string.
(Remember, C-style strings are null-terminated arrays).
Additional helpful notes:
strlen does not count the '\0' (That's why you need this extra byte). strcpy does copy the '\0'. char str[7] = "String"; - Adds '\0' by itself.char str[] = {'S','t','r','i','n','g'} - Does not add '\0'.char str[7] = {'S','t','r','i','n','g'} - Will add '\0'.In C based Strings there is always a special character at the end of string '\0' which also needs an extra byte. This is why we need an extra character and we need array of strlen(str)+1 to store the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With