Reputation:
I have seen other similar question but none of them solved my problem.
char name[30][15];
int i, n, found=0;
printf("Enter how many names you want to enter:");
scanf("%d", &n);
printf("Enter names of %d friends:", n);
for (i=0; i<n; i++)
scanf("%s", name[i]);
printf("Names are: ");
for (i=0; i<n; i++)
printf("%s\n", name[i]);
If I run this code, its runs properly but how can we input 1-D array when the array we defined is 2-D. Is the no of columns defined by default if we use name[i]
.
if I modify this code, it shows error.--
char name[30][15];
int i, n, found=0;
printf("Enter how many names you want to enter:");
scanf("%d", &n);
printf("Enter names of %d friends:", n);
for (i=0; i<n; i++)
scanf("%s", name[i][15]);
printf("Names are: ");
for (i=0; i<n; i++)
printf("%s\n", name[i]);
The output is--
Enter how many names you want to enter:2
Enter names of 2 friends:vyom
Names are:
Upvotes: 0
Views: 46
Reputation: 821
scanf("%s", name[i][15]);
is different compared to scanf("%s", name[i]);
type of name[i][15]
is char
and type of name[i]
is char*
scanf
expects char*
when reading strings, that is the reason in the second case its not behaving as you expected.
Use scanf("%s", name[i]);
for reading strings, better yet use fgets to read multi word strings.
Upvotes: 3