+ 4
A secret C++ question ( 5 )
What is the output of this code? cout<< sizeof("Solo"); cout<< strlen("Learn"); My answer is 45 but the right answer is 55 😭
6 Antworten
+ 16
because sizeof count '\0' or null terminated character which is automatically added on the end of every string
+ 2
Thanks,I am so foolish...
+ 2
I also would've said 45 to be honest.
I don't know for sure, but I guess a string directly used in sizeof (I mean without variable) contains a terminator ('\0'), while strings (datatype string) doesn't need this, because it is limited by the allocated memory for the variable.
string str = "solo";
cout << sizeof(str); //-> 4 bytes allocated => output 4
cout << sizeof("solo"); //-> 5 bytes, because the program needs to know when the string ends. so it's actually "solo\0"
It's just a guess. I would also like to read an actual explanation for this.
edit: thanks vukan ^^
+ 1
Yeah vukan is right
+ 1
No actually you’re not. That’s an error. Sizeof shouldn’t do that.
+ 1
solo\0
5
strlen just count the characters