C Array of Strings
In this page:
Declaring an Array of Strings
A declaration like char names[5][20] reserves room for 5 strings of up to 19 visible characters each (plus the null terminator) -- it's rigid but simple, unlike an array of char pointers which lets each string have its own independently-sized buffer.
Example: Declaring an Array of Strings
#include <stdio.h>
int main() {
char names[5][20];
printf("%zu", sizeof(names));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Initializing String Arrays
Each string literal in the initializer list is automatically padded with unused bytes if it's shorter than the row width you declared, wasting a little memory but keeping every row the same fixed size for predictable indexing.
Example: Initializing String Arrays
#include <stdio.h>
int main() {
char names[3][20] = {"Ann", "Bob", "Cat"};
printf("%s", names[1]);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Accessing Strings inside the Array
names[2] gives you a pointer to the start of the third string in the array, which you can pass directly to functions like printf("%s", names[2]) or strlen(names[2]) exactly as you would any other string.
Example: Accessing Strings inside the Array
#include <stdio.h>
int main() {
char names[3][20] = {"Ann", "Bob", "Cat"};
printf("%s", names[2]);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Modifying Strings in the Array
Attempting names[2] = "NewValue" is a compile error for a fixed 2D char array because you cannot reassign an array row as if it were a pointer -- strcpy(names[2], "NewValue") is the correct way to replace a row's contents in place.
Example: Modifying Strings in the Array
#include <stdio.h>
#include <string.h>
int main() {
char names[3][20] = {"Ann", "Bob", "Cat"};
strcpy(names[2], "NewValue");
printf("%s", names[2]);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Looping through String Arrays
A simple for loop from 0 to the row count lets you print or process each name; just be careful that whatever function you call inside the loop doesn't write more characters than the fixed row width can hold.
Example: Looping through String Arrays
#include <stdio.h>
int main() {
char names[3][20] = {"Ann", "Bob", "Cat"};
for (int i = 0; i < 3; i++) {
printf("%s ", names[i]);
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: