Old - Old-Style C Strings In the C programming language,...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Old-Style C Strings In the C programming language, and in older versions of C, there was not a string class. We had to store strings of characters in a different format, namely an array of characters. These arrays were a special kind of array, in that they had a terminating character in the position following the last valid character. We would declare an array of characters (not a C string) as follows: char name[10]; This can hold up to 10 characters, we could have initialized it when we declared it as follows: char name[10]={'M','a','r','k'}; This would store the four characters of my name as an array of characters. However, this is not how a C string is declared. To declare a c-string that will hold my name, we would do the following: char name[10]="Mark"; This actually stores 5 characters into the array, M a r k 0 ? ? ? ? ? The fifth character is the NULL character, which has the ASCII code of 0. The ?'s are just written to show that there is garbage stored in those locations. You might be tempted to do the following: char name[4]="Mark"; As we will see in the next slide, this is not correct! C-Strings This would attempt to store the four characters in the name, and then store the NULL character.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
However, there is not enough room in our array to store the five characters needed. We would have an access violation, and depending on your operating system, you will either get a run-time error, or the NULL character would be stored in the next byte of memory that follows the array called name, overwriting what ever was already there. Either way, this is a problem! Therefore, we must be careful to declare a c-string so that it can hold the string of characters that we want, along with the NULL character. This leads to wasted space. If you were going to store a last name, you
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 7

Old - Old-Style C Strings In the C programming language,...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online