2

I've noticed a weird discrepancy in C++.

Say I have this code:

const char myChars[] = "12345";
std::cout << myChars;

The output is: 12345

However, if I then change it to:

const char myChars[] = {'1','2','3','4','5'};
std::cout << myChars;

Then the output is: 12345__SOME_RANDOM_DATA_IN_MEMORY__

Why is it that cout appears to know the length of the first version but not the length of the second version? Also, does cout even know the length?

Thanks.

Paul R
  • 208,748
  • 37
  • 389
  • 560
Kyle
  • 3,935
  • 2
  • 30
  • 44

5 Answers5

22

There is no null terminator in your second example.

const char myChars[] = {'1','2','3','4','5', 0};

would work fine.

Strings literals require a null-terminator to indicate the end of the string.

See this stackoverflow answer for more detailed information: https://stackoverflow.com/a/2037245/507793

As for your first example, when you make a string literal using quotes like "Hello", that is roughly equivalent to {'H', 'e', 'l', 'l', 'o', 0}, as the null-terminator is implicit when using quotes.

Community
  • 1
  • 1
Matthew
  • 24,703
  • 9
  • 76
  • 110
  • 3
    To be pedantic, `0` is **not** the null terminator, `'\0'` is. Even though they have the same value, I think `'\0'` would be preferable since it is of type `char` rather than `0` which is of type `int`. – Jesse Good Jan 10 '13 at 21:23
  • @JesseGood Just for fun, in C, the type of `'\0'` *is* `int`, isn't it? – fredoverflow Jan 18 '13 at 19:57
  • 1
    @FredOverflow: True, but there is another difference. `'\0'` is an `octal escape sequence` while `0` is an `octal digit`. Octal escape sequences primary use is for nonprintable characters. – Jesse Good Jan 18 '13 at 20:30
4

Ask the compiler for sizeof(myChars) and notice the difference. The end of a string is marked by a null character, implicit when you use "".

Marc Glisse
  • 7,550
  • 2
  • 30
  • 53
2

When setting mychars[] with "12345", you implicitly add a '\0' to the end of it, telling the program that this is the end of the string, wich you dont with {'1','2','3','4','5'};

tomahh
  • 13,441
  • 3
  • 49
  • 70
2

C strings are implemented as char arrays that end with a special character \0.

String literals have it implicitly. While the curly braces array initialization doesn't add it.

You need to add it manually

const char myChars[] = {'1','2','3','4','5', '\0'};

or simply

const char myChars[] = {'1','2','3','4','5', 0};

Since '\0' == 0 numerically.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
2
const char myChars[] = {'1','2','3','4','5','\0'};

do not forget to add null terminate string

MOHAMED
  • 41,599
  • 58
  • 163
  • 268