4

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!

Kyuu
  • 953
  • 6
  • 15
  • 25

4 Answers4

11

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.

haccks
  • 104,019
  • 25
  • 176
  • 264
2

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);
        }
     }
  }
Lee Daniel Crocker
  • 12,927
  • 3
  • 29
  • 55
1

scanf returns number of successful readed parameters;

use 2D array for string-array

Never go out of bounds array

#include <stdio.h>

//Use defines or constants!
#define NUM_STRINGS 10
#define MAX_LENGTH_OFSTRING 1000

int main() {
    char variable[NUM_STRINGS][MAX_LENGTH_OFSTRING +1 /*for '\0' Null Character */];
    int i = 0;

    printf("enter a variable\n");
    while(scanf("%s", variable[i]) > 0){//if you print Ctrl+Z then program finish work. Do not write more than MAX_LENGTH_OFSTRING symbols
        printf("The variable entered was: %s\n",variable[i]);
        i++;
        if(i >= NUM_STRINGS)
            break;
    }
return 0;
}
Konstantin Dedov
  • 427
  • 3
  • 12
1

variable[0] has just stored first letter of string. If you want to store multiple strings in an array you can use 2D array. it has structure like

arr[3][100] = { "hello","world", "there"}

and you can access them as

printf("%s", arr[0]); one by one.

Onic Team
  • 1,620
  • 5
  • 26
  • 37