Can someone help me ?

Could someone explain why this is "new char[_length + 1];".

1
2
3
4
5
6
  myString(char *init_val)
	{
		_length = strlen(init_val);
		str = new char[_length + 1];
		strcpy(str, init_val);
	}
One character for string terminator character ('\0').
I think that the strlen(init_val) contains terminator charater ('\0). We don't have to add 1.
I think that the strlen(init_val) contains terminator charater ('\0). We don't have to add 1.

You think wrongly. Please visit documentation before espousing your belief.
strlen() does not include the terminating null character.
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char str[] = "abc";
    cout << "sizeof(str) = " << sizeof(str) << "\n";
    cout << "strlen(str) = " << strlen(str) << "\n";
}
sizeof(str) = 4
strlen(str) = 3

Topic archived. No new replies allowed.