This is a very strange question for me. Here's a brief explanation: I have a friend who wrote this program that reads data in from a game for a stats display. He uses classes and assigns a memory address to that class. In his class he has a variable for player names which are in ascii. He declares it like so:
I've played with his source and ive used a print function to print the name and it works, no matter the name length. So the above declaration is supposed to be an unsigned char, which takes up 1 byte, with his array set to 1 element. Meaning there will be one element with a char, 1 byte total. So how can this possibly hold more than 1 character? I'm baffled. Can someone explain this phenomena to me?
unsigned char Name;
Alternatively when he has a name in unicode, he uses this declaration, which works too!:
unsigned short Name;
It's undefined behaviour. You are writing past the end of the array, and corrupting memory. It may work for now, but is not guranteed to, and is extremely bad to rely on this behaviour.
Usually works. But is also undefined behaviour.
a = 10;
Alright, well I can see how it is bad programming and such, but why does it work and how? You're only declaring a single byte but when you use cout or sprintf, it recognizes a full 16 byte ascii string in memory and prints it correctly. It just makes no sense. =/
A C string is a null-terminated string of chars. When you pass it to functions, you are only passing a pointer. The receiving function has no idea of it's length. Eg, cout just reads all the way til it reaches a nul (or "\0"). When you use cin, it just writes all the char sequentially, and tack on a "\0" at the end. It doesn't know how long the array is (how much memory is actually allocated).
Undefined behaviour means it could work, it could crash, it could corrupt the memory and mess up the rest of the program (actually changing other variables), it could make your computer explode... you get the idea. All depends on the compiler, OS, temperature, relative humidity, whether theres an eclipses...
In short, don't do it.