C - String String Variables

Introduction

C has no specific variable type for strings and there are no special operators for processing strings.

You use an array of type char to hold strings.

You can declare an array variable like this:

char saying[20];

This variable can store a string that contains up to 19 characters, because you must allow one element for the termination character.

If you use this array to store 20 characters that are not a string.

The dimension of an array that you intend to use to store a string must be at least one greater than the number of characters.

The compiler automatically adds \0 to the end of every string constant.

char saying[] = "This is a string.";

The compiler will assign a value to the dimension that is sufficient to accommodate the initializing string constant.

In this case it will be 18, which is 17 elements for the characters in the string plus an extra element for the terminating \0.

You can initialize part of an array of elements of type char with a string. For example:

char str[40] = "To be";

The compiler will initialize the first five elements, str[0] to str[4], with the characters of the string constant.

str[5] will contain the null character, '\0'.

Space is allocated for all 40 elements of the array, and they're all available to use in any way you want.

The following code creates a char array and declares it as constant:

const char message[] = "The end of the world is nigh.";

To refer to the string stored in an array, use the array name by itself.

For instance, to output the string stored in message using the printf() function, you could write this:

printf("\nThe message is: %s", message);

The %s specification is for outputting a null-terminated string.

Example

Exercise