简体   繁体   中英

how to store and then print a 2d character/string array?

Suppose I have the words: tiger, lion, giraffe.

How can I store it in a two dimensional char array using for loop and scanf and then print the words one by one using a for loop?

Something like

for(i=0;i<W;i++)
{
    scanf("%s",str[i][0]);  //to input the string
}

PS Sorry for asking such a basic question, but I couldn't find a suitable answer on Google.

First you need to create an array of strings.

char arrayOfWords[NUMBER_OF_WORDS][MAX_SIZE_OF_WORD];

Then, you need to enter the string into the array

int i;
for (i=0; i<NUMBER_OF_WORDS; i++) {
    scanf ("%s" , arrayOfWords[i]);
}

Finally in oreder to print them use

for (i=0; i<NUMBER_OF_WORDS; i++) {
    printf ("%s" , arrayOfWords[i]);
}
char * str[NumberOfWords];

str[0] = malloc(sizeof(char) * lengthOfWord + 1); //Add 1 for null byte;
memcpy(str[0], "myliteral\0");
//Initialize more;

for(int i = 0; i < NumberOfWords; i++){
    scanf("%s", str[i]);
 } 

You can do this way.

1)Create an array of character pointers.

2)Allocate the memory dynamically.

3)Get the data through scanf. A simple implementation is below

#include<stdio.h>
#include<malloc.h>

int main()
{
    char *str[3];
    int i;
    int num;
    for(i=0;i<3;i++)
    {
       printf("\n No of charecters in the word : ");
       scanf("%d",&num);
       str[i]=(char *)malloc((num+1)*sizeof(char));
       scanf("%s",str[i]);
    }
    for(i=0;i<3;i++)  //to print the same 
    {
      printf("\n %s",str[i]);    
    }
}
#include<stdio.h>
int main()
{
  char str[6][10] ;
  int  i , j ;
  for(i = 0 ; i < 6 ; i++)
  {
    // Given the str length should be less than 10
    // to also store the null terminator
    scanf("%s",str[i]) ;
  }
  printf("\n") ;
  for(i = 0 ; i < 6 ; i++)
  {
    printf("%s",str[i]) ;
    printf("\n") ;
  }
  return 0 ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM