Skip to main content
Logo image

Section 20.1 Declaring and Initializing Strings

Suppose you wanted to store a name (for example "Petra") in the computer’s memory. Of course you could simply declare five individual characters and assign the letters of the name to them. But that’s not very convenient and we already know that an array of characters would be a much better option. We could then simply use a loop to print out all of the characters one-by-one. The only slight issue would be that we’d have to keep track of the length of the name somewhere in order to be able to tell the loop how many times to run. Not a huge deal really, and we are already used to doing so for other arrays.
But C actually provides some additional functionality for storing so-called strings that makes it unnecessary to separately keep track of the length of the string. How? An extra character (the null terminator \0) is placed after the last character in the array in order to indicate the end of the string. And so:
A string is an array of type char that is terminated with the null character \0. By the way, the null terminator (character) is the character in the ASCII table with ASCII code 0.
We have already been using string constants (that cannot be changed), for example:
printf("This is a string constant.\n");
But it is very useful to have variables that can hold strings (for example, filenames). In the following example we use a variable of type string (so really, an array of characters), to hold a first name and a last name. You can see from the example how you can initialize such a variable at declaration time. Sadly things won’t be quite as easy elsewhere in our code but more on that later.

admin.....open in new window

Investigate 20.1.

How much space is allocated in memory for the string firstName if each char uses 1 byte?