0

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:
1
  • BTW, please add braces to ALL for loops. It makes the code easy to read and less bug-prone. And keep indentation consistent - it doesn't make sense to further nest printf at all given that it should probably be at the outermost indentation. Commented Dec 8, 2020 at 11:13

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

so I defined it as char name[30][15];, then I can change to to char* right?
can you explain what is happening, I used a char array char name[30][15];, then I used name[i] to read input for the 2-D array, please just a little detail.
char name[30][15] means name is an array of characters in which you can store 30 strings each with length of 15 including \0,the each string is accessed using name [ i ] where i ranges from 0 - 29 and name [ i ][ j ] refers to a jth character in ith string, so name[i] refers to the address of ith string , so it works when used in scanf. if this is still not clear, please open a new post asking for any doubts,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.