C – String

Home/C - Tutorial/C – String
C – String 2017-07-19T22:25:31+00:00

String :

A string in C is actually a character array. As an individual character variable can store only one character, we need an array of characters to store strings. Thus, in C string is stored in an array of characters. Each character in a string occupies one location in an array. The null character ‘\0’ is put after the last character. This is done so that program can tell when the end of the string has been reached. For example, the string ”I Like C Programming” is stored as follows.

I L i k e C P r o g r a m m i n g \o

Since the string has 20 characters (including space), it requires an arrayof at least, size 21 to store it.

Thus, in C, a string is a one-dimensional array of characters terminated a null character. The terminating null character is important. In fact, a string not terminated by ‘\0’ is not really a string, but merely a collection of characters.

                      A string may contain any character, including special control characters, such as \n, \t, \\ etc…

                      There is an important distinction between a string and a single character in C. The convention is that single characters are enclosed by single quotes e.g. ‘*’ and have the type char. Strings, on the hand, are enclosed by double quotes e.g. “name” and have the type “pointer to char” (char *) or array of char.

                      Strings can be declared in two main ways; one of these is as an array of characters, the other is as a pointer to some pre-assigned array. Perhaps the simplest way of seeing how C stores arrays is to give an extreme example which would probably never be used in practice.

                          This method of handling strings is perfectly acceptable, if there is time to waste, but it is so laborious that C provides a special initialization service for strings, which bypasses the need to assign every single character with a new assignment!.

The other way is use a pointer to some pre-assigned array.


Prev Next