Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocate space for char

Tags:

c++

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?

like image 954
JohnnyZhang Avatar asked Nov 16 '12 15:11

JohnnyZhang


2 Answers

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'.
like image 75
Maroun Avatar answered Oct 22 '22 08:10

Maroun


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.

like image 33
Mohit Sehgal Avatar answered Oct 22 '22 08:10

Mohit Sehgal