C – String 2017-08-05T20:55:16+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 string. Thus, in C strings are stored in an array of characters. Each character 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 array of at least, size 21 to store it.

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

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

                      There is an important distinction between a strings 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