8.2 Defining Strings
Although C does not have a built-in type for defining strings, we can create variables that store strings. To do this, you define a character array
- const int NAME_SIZE = 36; // this would be placed above the main function
- char name[NAME_SIZE];
which must be large enough to store all of the characters in the string plus the null character. Here, the name variable can store a string that contains up to 35 characters, plus the required null character:

The null character is not considered part of the string. It is only used within the underlying character array to indicate the end of the character sequence that comprises the string. An array storing a string must have sufficient capacity to store the maximum expected string length plus the null character.
Initializing a Character Array
A character array used to store a string can be initialized with a literal string when it's declared. For example, the array declarations
- char message[] = "Hello";
- char student[NAME_SIZE] = "John Smith";
results in the two arrays
A character array can also be initialized to the empty string
- char empty[20] = "";
which results in the null character being stored in the first element of the array.
Printing Strings
A string stored in a character array can be printed using the printf function and the %s format specifier in the same way a literal string can
- printf("Student: %s\n", student);
Unlike in Python, no type checking is performed when using the printf or fprintf function. Thus, you are responsible for making sure that the argument passed to the function for the %s format specifier is in fact a null-terminated character array.
Consider the three variable declarations below and answer the following questions
- int x = 4;
- char c = '4'
- char num[] = "4";
- Do all three of the literals represent the same value?
- Draw the memory representation of the three variables.
4, one is the character 4, and the third is a string containing the character 4.
Consider the character array representation below which stores a string
How many characters are in the string?
- 0
- 5
- 6
- 9
There are five characters preceding the null character, which is not part of the string.
Consider the character array representation below
How many characters are in the string?
- 0
- 5
- 6
- 9
There are no characters preceding the null character, which makes this an empty string.
Consider the code segment
- char fruit[9];
- printf("%s\n", fruit);
which contains a logic error. Identify the error.
The fruit array has not been initialized to contain a string and thus, may not contain the null character. The results are unpredictable when you attempt to print a character array that does not contain a string.

