Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store string into array in c

Tags:

arrays

c

As i know, i can create an array with item inside such as:

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

but how can i store my input into array like code above because i only can code it as

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

and it store each char into each space.

How can i store the input "HELLO" such that it stores into input[0] but now

H to input[0],E to input[1], and so on.

like image 646
MoonScythe Avatar asked Jan 27 '14 09:01

MoonScythe


People also ask

Can you store strings in an array in C?

When strings are declared as character arrays, they are stored like other types of arrays in C.

Can I store string in an array?

Answer: Yes. Just like arrays can hold other data types like char, int, float, arrays can also hold strings. In this case, the array becomes an array of 'array of characters' as the string can be viewed as a sequence or array of characters.

Can you store a string in char C?

Overview. The C language does not have a specific "String" data type, the way some other languages such as C++ and Java do. Instead C stores strings of characters as arrays of chars, terminated by a null byte.


1 Answers

You need a 2 dimensional character array 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]);
}
like image 92
cybermage14 Avatar answered Oct 07 '22 13:10

cybermage14