donderdag 14 juni 2007

C-style string

A string, or especialy a C-style string is a series of characters stored in consecutive bytes of memory.

The idea of a series of characters stored in consecutive bytes implies that you can store a string in an array of data-type char. With each character kept in its own array element.

Strings provide a conveniant way to store text information, such as messages to the user, or responses from the user.

C-style strings have a special property, they all end with a '\0' or ASCII character 0. This marks the end of the character string. This character is called the NULL CHARACTER.

consider the following two declarations:

char dog [5] = { 'b', 'e', 'a', 'u', 'x'}; // NOT a string
char cat[5] = { 'f', 'a', 't', 's', '\0'}; // YES, a string!

If you would send dog to cout, cout would display all 5 characters, and then continues with the next bytes in memory until it reach a null-buty, a byte which its value is zero. This can lead to unexpected results. Since it is true that bytes that are zero are seen a lot in memory, usualy quick after printing some non zero values cout will stop when a byte is zero.

Initializing the arrays using the single quote technique described is a bit tedious, to solve that we can assign a quoted string, this makes it a lot easier!

char bird[11] = "Mr. Cheeps"; // the \0 is understood
char fish[] = "Bubbles"; // let the compiler count

Quoted strings always include the terminating null character implicitly, so you don't have to spell it out.

Also, the various C++ input facilities for reading a string from keyboard input into a char array automaticaly add the terminating null character for you!

char boss[8] = "Bozo";

Bozo\0\0\0\0 (This is what the compiler creates from initializing the too short string literal to boss.

It is generaly safer to let the compiler count the number of characters assigned to the array by a string constant. It protects against mistakes and the null byte is automaticaly added for you!

Don't confuse character constants like 'S' with string constants like "S", the latter includes also the null character while the first is just a single ASCII value correspondening to the character S.

Even worse, "S" actually represents the memory address at which the string constant is stored!

So a statement like:
char shirt_size = "S"; // illegal type mismatch
attemts to assign a memory address to shirt_size!!!
Because an address is a separate type in C++, a C++ compiler won't allow this sort of nonsense.

Geen opmerkingen: