A string array can store several C strings. One common form is a two-dimensional character array where each row has space for one null-terminated string.
#include <stdio.h>
int main(void) {
char names[4][20] = {"Alex", "Roan", "Allen", "Roman"};
for (int i = 0; i < 4; i++) {
printf("%s\n", names[i]);
}
return 0;
}
Output
Alex
Roan
Allen
Roman
The old gets() function is unsafe and was removed from the C standard. Use fgets() with the size of each row.
#include <stdio.h>
#include <string.h>
int main(void) {
char names[4][40];
for (int i = 0; i < 4; i++) {
printf("Enter name %d: ", i + 1);
if (fgets(names[i], sizeof names[i], stdin) == NULL) {
printf("Input error.\n");
return 1;
}
names[i][strcspn(names[i], "\n")] = '\0';
}
printf("\nStored names:\n");
for (int i = 0; i < 4; i++) {
printf("%s\n", names[i]);
}
return 0;
}
char names[4][40];
4 = number of strings.40 = maximum storage available for each string, including its null terminator.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.