Skip to main content
Logo image

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
char words[100][50];
The following video shows how to work with arrays of strings.

If you cannot see this codecast, please click here.

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
  • name = "Taylor";
    
  • Not quite. Try again!
  • name[0] = "Taylor";
    
  • Not quite. Try again!
  • strcpy(name[0][0], "Taylor");
    
  • Not quite. Try again!