1

I believe Array1 and Array2 are declared differently but they both do have the same type - char. Both Array1 and Array2 seem to contain the same exact values and the same amount of values. I don't understand why their length are different from each other. Can someone please explain why?

char Array1[ ] = { 1, 2, 3, 4, 5 };
char Array2[ ] = "\x01\x02\x03\x04\x05";

std::cout << "Length of Array1 = " << sizeof( Array1 )/sizeof( *Array1 )
          << std::endl
          << "Length of Array2 = " << sizeof( Array2 )/sizeof( *Array2 );

Output:

Length of Array1 = 5
Length of Array2 = 6
CLearner
  • 532
  • 1
  • 6
  • 17

2 Answers2

5

The second array has an extra character due to the implicit null terminating character present in the string literal.

From section 2.14.5 String literals of the C++11 standard (draft n3337) point 14 states:

After any necessary concatenation, in translation phase 7 (2.2), ’\0’ is appended to every string literal so that programs that scan a string can find its end.

hmjd
  • 120,187
  • 20
  • 207
  • 252
2

Because strings a NULL-treminated. You have extra character at string literal '\0'

kassak
  • 3,974
  • 1
  • 25
  • 36