Declaring and Initializing String Variables


C does not support strings as a data type. However it allows us to present strings as arrays of characters in C, thus, a string variable is any valid C variable name and is always declared as an array of characters. The most common form of string variable declaration is:

char string_name[size];

The size determines the number of characters in the string_name. Here are some examples:

char country[10];
char names[10];

When the compiler assigns a character string to a character array, it automatically returns a null character ('\ 0') at the end of the string. Thus, the size should be equal to the maximum number of characters in the string plus one.

Like number arrays, character arrays can be started after they are declared. C allows a character array to be started in any one of the following two forms:

char country[10] = "INDIA";
char country[10] = {'I','N','D','I','A','\0'};

The reason why the country had to be 10 elements long is that String INDIA has 5 characters. Note that we must explicitly provide a null terminator when we begin by listing the elements of a character array.

C allows us to start a character array without specifying the number of elements. In this case, the size of the array will be determined automatically based on the number of elements. For example, statements

char a[] = {'H','E','L','L','O','\0');

defines the array 'a' as a six element array.

We can also declare the size much larger than the string size in the initializer. That is, the statement

char a[10] = "HELLO";

is permitted. In this case, the computer creates a character array of size 10, places the value "HELLO" in it, terminates with the null character, and initializes all other elements to NULL. The storage look like :

H E L L O \0 \0 \0 \0 \0