I want to print the 3 city names by using matrix in C?
#include <stdio.h>
#include <stdlib.h>
int main() {
char city[15];
int i;
for(i=0;i<3;i )
{
printf("Enter the city");
scanf("%s",city[i]);
}
for(i=0;i<3;i )
{
printf("The city that was entered");
printf("%s",city[i]);
}
return 0;
}
CodePudding user response:
char is a single character, and char city[15] is an array of 15 characters.
To store 15 strings (one for each city name) it would need to be like char city[15][101]. This would allow 100 characters for each city name, plus the terminating 0 character. (Strings in C get a 0 char at the end).
Then scanf("%s",city[i]) would work.
However if the user enters more than 100 characters for the city name, it would cause a buffer overflow. A way to prevent this is to use scanf("0s",city[i]);.
