Read a String Array in C

In C, a string array can be read using various techniques such as character arrays, pointers, and standard input functions like scanf() and fgets(). We can store multiple strings in a two-dimensional character array and access them using loops.

In this tutorial, we will cover different methods to read and display a string array in C with examples.


Examples to Read a String Array

1. Reading a String Array Using scanf()

In this example, we will declare a 2D character array to store multiple strings, take input using scanf(), and display the stored strings.

main.c

</>
Copy
#include <stdio.h>

int main() {
    char strings[3][20]; // Array to store 3 strings with max length 19 + 1 for null character

    printf("Enter 3 words:\n");
    
    // Reading strings using scanf
    for (int i = 0; i < 3; i++) {
        scanf("%s", strings[i]); // Reads a single word (excluding spaces)
    }

    printf("\nYou entered:\n");
    for (int i = 0; i < 3; i++) {
        printf("%s\n", strings[i]); // Printing stored strings
    }

    return 0;
}

Explanation:

  1. We declare a 2D character array strings[3][20] to store 3 words, each up to 19 characters long.
  2. We use a for loop to iterate and read each word using scanf("%s", strings[i]).
  3. scanf() only reads a single word, ignoring spaces.
  4. We use another loop to print the stored strings one by one.

Output:

Enter 3 words:
apple banana cherry

You entered:
apple
banana
cherry

2. Reading a String Array Using fgets() (Recommended)

In this example, we will use fgets(), which is safer than gets(), to read an array of multiple strings while handling spaces properly.

main.c

</>
Copy
#include <stdio.h>

int main() {
    char strings[3][50]; // Array to store 3 sentences

    printf("Enter 3 sentences:\n");

    // Reading strings using fgets()
    for (int i = 0; i < 3; i++) {
        fgets(strings[i], sizeof(strings[i]), stdin);
    }

    printf("\nYou entered:\n");
    for (int i = 0; i < 3; i++) {
        printf("%s", strings[i]); // No need for \n, fgets() stores newline
    }

    return 0;
}

Explanation:

  1. We declare a 2D character array strings[3][50] to store 3 sentences.
  2. fgets(strings[i], sizeof(strings[i]), stdin) reads a full line, including spaces.
  3. sizeof(strings[i]) ensures we do not exceed the buffer size.
  4. We use a for loop to print each string.

Output:

Enter 3 sentences:
apple is red
sky is blue
you are awesome

You entered:
apple is red
sky is blue
you are awesome

Conclusion

In this tutorial, we covered multiple ways to read a string array in C:

  1. scanf() for reading single words.
  2. fgets() (recommended) for safe input handling.