+ 3
Printing an array of characters
I was curious about putting strings in a pointer of a character, so I tried this out: int main() { char *str = "Solo Learn"; for (int i = 0; i < 100; i++){ cout << i << ": " << str[i] << endl; } cout << "Program completed."; return 0; } I arbitrarily put i<100 because I was curious, and then the result ended up as if the string were "Solo Learn : Program completed. C POSIX basic_string::erase 7C α6C ╖6C ó6C 7C Q0C 00C 0C ≥/C " Then my "Program completed." line showed up. Why does it pick up all other strings in the program, and where do the other characters come from?
1 Antwort
+ 2
C++ does not have an automated control system for beeing outside of your String...See following example
This is the memory around and with your String.
Def. | memory space | ; x is a filled memory space with something we dont know
... | x | x | 'S' | 'o' | 'l' | 'o' | ' ' | 'L' | 'e' | 'a' | 'r' | 'n' | x | x | ...
By printing from i to 100 you are doing following:
cout << str[0]; // prints S
cout << str[1]; // prints o
...
cout << str[9]; // prints n
cout << str[10]; // prints now the content of the x stored behind your String. See here:
... | x | x | 'S' | 'o' | 'l' | 'o' | ' ' | 'L' | 'e' | 'a' | 'r' | 'n' | x | x | ...
^
str[10]
and so it is going on... That is the crazy stuff behind your String in the output result you got