Section 24.1 Arrays of Strings
Recall that in C, a string is a NULL-terminated array of characters. Therefore, if we wanted to store multiple strings in an array, we’d need an array of strings, which is an array of arrays! This is also called a two-dimensional array.
Such an array of strings is declared as follows:
char name[NRECS][STRLEN];
Here,
name is the name of the array,
NRECS the number of strings to store, and
STRLEN a bound on the length of the strings to be stored (remember to leave room for the NULL-terminator).
Table 24.1. An Array of Strings
P
e
t
r
a
\0
A
l
e
x
\0
C
h
o
c
o
l
a
t
e
\0
The above sample table has
STRLEN=10 and
NRECS=5.
You could
#define NRECS and
STRLEN at the top of your program if you wish, so that you could easily change these constants. For example:
#define NRECS 100
#define STRLEN 50
char words[NRECS][STRLEN];
declares an array of strings that can hold 100 strings of maximum length 50 characters (including the NULL-terminator). You could also simply write
The following video shows how to work with arrays of strings.
If you cannot see this codecast, please click here .
Aside: Video Description.
To store one word we need a string, which is a one-dimensional array. Thus to store multiple words we need either multiple one-dimensional arrays or one two-dimensional array
Multidimensional arrays can be initialized using loops
NEW SYNTAX: the following line declares an array of strings, with [NRECS] = number of records and [STRLEN] = max. string length
char name[NRECS][STRLEN];
Check Your Understanding Check Your Understanding
1.
Suppose you have declared an “array of strings” using the command
char name[100][30];
If you wanted to store the name “Taylor” in the topmost position of this array, how would you do so?
strcpy(name[0], "Taylor");
Correct
Not quite. Try again!
Not quite. Try again!
strcpy(name[0][0], "Taylor");
Not quite. Try again!