Before I continue, here's the code:
#include <iostream> using namespace std; int main() { char array[] = {'a','b','c'}; cout << array << endl; return 0; } My system:
- VisualStudio 2019, default C++ settings
- Using Debug build instead of release
When I run this code sample, I get something like this in my console output:
abcXXXXXXXXX Those X's represent seemingly random characters. I know they're from existing values in memory at that address, but I don't understand why I'm getting 12 bytes back instead of the three from my array.
Now, I know that if I were doing this with ints which are four bytes long, maybe this would make sense but sizeof(array) returns three (ie. three bytes long, I know the sizeof(array) / sizeof(array[0] trick.) And when I do try it with ints, I'm even more confused because I get some four-byte hex number instead (maybe a memory address?)
This may be some trivial question, I'm sorry, but I'm just trying to figure out why it behaves like this. No vectors please, I'm trying to stay as non-STL as possible here.
cout << array[0] << array[1] << array[2] << endl;char*pointer when you pass it tocout, which is then expected to be a null-terminated C-style string. Also remember that C++ offers zero protection against reading an array out of bounds, and weird things can happen when you do.