Wednesday, November 2, 2011

What are Strings in C programming language

The way a group of integers can be stored in an integer array, similarly a group of characters can be stored in a character array. Character arrays are many a time also called strings. Many languages internally treat strings as character arrays, but somehow conceal this fact from the programmer. Character arrays or strings are used by programming languages to manipulate text such as words and sentences. A string constant is a one-dimensional array of characters terminated by a null ( ‘\0’ ). For example,

char  name[ ] = { 'H', 'A', 'E', 'S', 'L', 'E', 'R', '\0' } ;

Each character in the array occupies one byte of memory and the last character is always ‘\0’. What character is this? It looks like two characters, but it is actually only one character, with the \ indicating that what follows it is something special. ‘\0’ is called null character. Note that ‘\0’ and ‘0’ are not same. ASCII value of ‘\0’ is 0, whereas ASCII value of ‘0’ is 48. Figure 9.1 shows the way a character array is stored in memory. Note that the elements of the character array are stored in contiguous memory locations.  The terminating null (‘\0’) is important, because it is the only way the functions that work with a string can know where the string ends. In fact, a string not terminated by a ‘\0’ is not really a string, but merely a collection of characters. 



C concedes the fact that you would use strings very often and hence provides a shortcut for initializing strings. For example, the string used above can also be initialized as,

char  name[ ] = "HAESLER" ;

Note that, in this declaration ‘\0’ is not necessary. C inserts the null character automatically.

No comments:

Post a Comment