Save string in array in c

As I know, I can create an array with an element inside, for example:

char *test1[3]= {"arrtest","ao", "123"}; 

but how can I store my input in an array, like the code above, because I can encode it like

 input[10]; scanf("%s",&input) or gets(input); 

and saves every char to every space.

How can I save the input "HELLO" so that it is saved at the input [0], but now

H for input [0], E for input [1], etc.

+7
c arrays
source share
6 answers

You need a 2-dimensional array of characters to have an array of strings:

 #include <stdio.h> int main() { char strings[3][256]; scanf("%s %s %s", strings[0], strings[1], strings[2]); printf("%s\n%s\n%s\n", strings[0], strings[1], strings[2]); } 
+6
source share

Use a 2-dimensional array of char input[3][10];
or
an array of char pointers (for example, char *input[3]; ) that must be dynamically allocated in memory before any value is stored in these places.

First case, enter the input values ​​as scanf("%s", input[0]); , similarly for input[1] and input[2] . Remember that you can save a string of maximum size 10 (including the character '\0' ) in each input[i] .

In the second case, enter the input in the same way as above, but allocate memory for each pointer input[i] , using malloc before. Here you have size flexibility for each row.

+2
source share

I do not understand what you need. But here is what I guessed.

 char *a[5];//array of five pointers for(i=0;i<5;i++)// iterate the number of pointer times in the array { char input[10];// a local array variable a[i]=malloc(10*sizeof(char)); //allocate memory for each pointer in the array here scanf("%s",input);//take the input from stdin strcpy(a[i],input);//store the value in one of the pointer in the pointer array } 
0
source share

try below code:

 char *input[10]; input[0]=(char*)malloc(25);//mention the size you need.. scanf("%s",input[0]); printf("%s",input[0]); 
0
source share
 int main() { int n,j; cin>>n; char a[100][100]; for(int i=1;i<=n;i++){ j=1; while(a[i][j]!=EOF){ a[i][j]=getchar(); j++; } } 
0
source share

This code inspired me on how to get user input strings into an array. I am new to C and this board, I apologize if I do not follow some rules for posting comments. I'm trying to figure it out.

 #include <stdio.h> int main() { char strings[3][256]; scanf("%s %s %s", strings[0], strings[1], strings[2]); printf("%s\n%s\n%s\n", strings[0], strings[1], strings[2]); } 
0
source share

All Articles