0

Can Someone explain why sizeof operator gives wrong return in value in following code in c++. Although the expected answer was 6, the final output was 7.

char word[]="SanCha";
cout << sizeof(text);

Evg
  • 25,259
  • 5
  • 41
  • 83
  • 2
    I would expect this code not to compile at all. – Evg Mar 06 '22 at 08:26
  • Because of the terminating '\0'. The variable name was `word`, not `text`. – Attersson Mar 06 '22 at 08:50
  • By convention, a string literal is represented as a (statically) allocated array of `char` with a terminating nul (with numeric value zero) character. So `"SanCha"` is represented as an array with elements `{'S', 'a', 'n', 'C', 'h', 'a', '\0'};` which has size `7`, not `6`. C++ inherited this from C, hence need for functions like `strcmp()`, `strlen()`, `strcpy()`, `strcat()`, etc to work with string literals and arrays of `char` that represent similar strings. – Peter Mar 06 '22 at 12:24

0 Answers0