Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - how to store multiple strings in an array

Tags:

arrays

c

string

Wondering how store different strings in an array. For example a user would input 'qwe' and the program would then store that in an array variable[0]. Entering another string would then store it as variable[1] and so on

int
main(int argc, char *argv[]) {
    char variable[1000];
    int i;

    printf("enter a variable\n");
    scanf("%s", variable);
    for (i = 0; ??? ;i++) {


        printf("The variable entered was: %s\n",variable[i]);
    }
return 0;

Im new to C so I have no idea what im doing. but thats what I have came up with so far and was wondering if I could get some help with filling in the rest Thanks!

like image 605
Kyuu Avatar asked Dec 06 '22 22:12

Kyuu


2 Answers

You can use 2D array to store multiple strings. For 10 strings each of length 100

char variable[10][100];

printf("Enter Strings\n");
for (int i = 0; i < 10 ;i++)  
    scanf("%100s", variable[i]); 

Better to use fgets to read string.

fgets(variable[i], sizeof(variable[i]), stdin);  

You can also use dynamic memory allocation by using an array of pointers to char.

like image 93
haccks Avatar answered Dec 28 '22 00:12

haccks


The most efficient way is to have an array of character pointers and allocate memory for them as needed:

char *strings[10];

int main(int ac, char *av[]) {
    memset(strings, 0, 10 * sizeof(char *));

    for (int i = 0; i < 10; i += 1) {
        char ins[100];
        scanf("%100s", ins);

        strings[i] = malloc(strlen(ins) + 1);
        if (strings[i]) {
            strcpy(strings[i], ins);
        }
     }
  }
like image 32
Lee Daniel Crocker Avatar answered Dec 28 '22 01:12

Lee Daniel Crocker