Arrays of Strings
Arrays of Strings are special uses of 2D Arrays where each row is an entire C-style string, allowing us to store a collection of language!
Declaration
The syntax for an array of strings declaration is exactly the same as 2D array declarations. The biggest difference is related to the abstraction of what it’s used for: language. </p>
For example, for a song playlist, we can declare a 2D array:
char playlist[8][100];
where the row size 8
is the number of songs (and should be replaced with a macro likeNUM_SONGS
). The column size 100
is the "arbitrarily large" capacity for each song name (and should be replaced with a macro like STR_CAP
).
Accessing Elements
We can look at individual letters in the strings in the same way as other 2D Arrays. Continuing our example, if we wanted to check which songs started with certain letters, we could do something like this:
for(int songIndex = 0; songIndex < NUM_SONGS; songIndex++){
if(playlist[songIndex][0] == 'A'){
printf("Song %d starts with an A.\n", songIndex + 1);
}
}
Accessing All Elements
Accessing each element in an array of strings is a little different than with a regular 2D array, since we cannot know the string length in advance. Therefore, instead of being controlled by the column size, the inner for
loop should rely on finding the null character \0
for stopping, like so:
int spaceCounter = 0;
for(int songIndex = 0; songIndex < NUM_SONGS; songIndex++){
for(int stringIndex = 0; board[songIndex][stringIndex] != '\0'; stringIndex++){
if(board[songIndex][stringIndex] == ' '){
spaceCounter++;
}
}
}
Slicing Arrays
Since each row of the 2D Array is a C-style String, that row can be treated just like one! This is different than accessing a single element, or char
, in the array. Instead, we're referring to the beginning of each row, which is often called slicing the array because we're isolating one slice or row in a 2D array.
Continuing our song example, to display each of the the songs in the playlist array, we just need to send each row to the printf
function:
for(int songIndex = 0; songIndex < NUM_SONGS; songIndex++){
printf("%d: %s.\n", songIndex + 1, playlist[songIndex]);
}