Some Char Array Difference

I want to ask if
 
  char word[] = {'H','e','l','l','o','\0'};

and
 
  char word[] = {'H','e','l','l','o'};

have any difference
AND
if
 
  cout << text;

and
 
  cout << text.c_str();

have any difference??
Because in my compiler when I test it I dont feel any difference
Thanks
Last edited on
For your first part: The difference is the first word[] array will print correctly through cout<<, and the other one is undefined behavior when printed, because it is not properly null-terminated.
Note that your first excerpt is equivalent to char word[] = "Hello";, which is properly null-terminated implicitly.
c-strings rely on the null termination to know where to stop. The program might still work without it, but that's just because the next character in memory just so happened to be a 0. This could crash your program (or worse, it won't).

if
cout << text;
and
cout << text.c_str();
have any difference


Yes, check this out:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>

int main()
{
    using namespace std;
    string text = "hello world";
    text[6] = '\0'; // replace the 'w' with a null character
    
    cout << text << '\n';
    cout << text.c_str() << '\n';
}


std::strings lengths are stored separately, and do not need to be null-terminated. The c_str() will be properly null-terminated either way.
Last edited on
^^ what he said. Ganado and I often cross each other posting at about the same time :)
Last edited on
Topic archived. No new replies allowed.