In C, how to print a string from a multidimensional array? -


i have following program take 5 user entered names , print them out.

i need ask each name 1 one, prompt user either print list of names or add name list. names must stored in 2 dimensional array, though don't see why couldn't done regular array.

my code accepts names no issues, fails print anything. includes print tests monitor error happens. test number 6 not print, there must issue printf("name: %s", names[x][y]);

what error?

#include <stdio.h>      int main() {     int x;     int y;     char names[5][51] = {{'\0'},{'\0'}};      printf("enter names: ");     (x = 0; x <5; x++) {         printf("\nprinttest 1");         (y = 0; y < 1; y++) {         printf("\nprinttest 2");             scanf("%50s",&names[x][y]);         }     }     printf("\nprinttest 3");      (x = 0; x < 5; x++) {         printf("\nprinttest 4");         (y = 0; y < 1; y++) {             printf("\nprinttest 5");             printf("name: %s", names[x][y]);             printf("\nprinttest 6");         }     } } 

so here's analysis

your mistake:

in fact declared 2d array each xth index char*.

  • if use names[x], char* pointer @ xth element of names.
  • if use names[x][y] pointer @ xth element , access it's yth element character , character datatype printed %c not %s.

possible solution:

if want print arrays character character, need iterate inner loop on size of array 51 in case, , can print array using %c instead of %s.

or can print whole array using %s but in case inner loop not required because printing whole array @ time.

updated code:

method # 01:

//iterating on char* (x = 0; x < 5; x++) {         printf("\nprinttest 4");          //use of inner loop - printing arrays character character         (y = 0; y < 51; y++)         {             printf("\nprinttest 5");             printf("name: %c", names[x][y]);             printf("\nprinttest 6");         } } 

method # 02:

//iterating on char* (x = 0; x < 5; x++) {         printf("\nprinttest 4");          //printing arrays without loop         printf("\nprinttest 5");         printf("name: %s", names[x]);         printf("\nprinttest 6"); } 

hope clear now.


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -