how to store and then print a 2d character/string array?
66,311
Solution 1
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]);
}
Solution 2
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]);
}
Solution 3
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]);
}
}
Solution 4
#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 ;
}
Author by
guitar_geek
Updated on July 09, 2022Comments
-
guitar_geek almost 2 years
Suppose I have the words: tiger, lion, giraffe.
How can I store it in a two dimensional
char
array usingfor
loop andscanf
and then print the words one by one using afor
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.