• Home
  • 5.17 Array of Strings

5.17 Array of Strings

View Categories

5.17 Array of Strings

An array of strings can be represented in C using a two-dimensional character array. Each row stores one null-terminated string, with the row size determining the maximum storage available for each string.

#include <stdio.h>

int main(void)
{
    char names[3][20] = {
        "Alice",
        "Bob",
        "Charlie"
    };

    for (int i = 0; i < 3; i++)
    {
        printf("%s\n", names[i]);
    }

    return 0;
}

Example Output #

Alice
Bob
Charlie

Explanation #

The declaration:

char names[3][20];

creates three character arrays, each containing 20 elements.

Each row can store up to 19 string characters plus the terminating null character '\0'.

The initialization:

char names[3][20] = {
    "Alice",
    "Bob",
    "Charlie"
};

stores one string in each row. Any remaining elements in each initialized row are set to zero.

The expression names[i] refers to the character array at row i. In the printf() call, it converts to a pointer to the first character, which is suitable for the %s conversion specifier because the row contains a null-terminated string.

Array of Strings: Common Representations #

Declaration Description
char names[3][20]; Three writable character arrays, each with capacity for 19 characters plus '\0'
char *names[3]; Array of three pointers to characters
const char *names[] = {"Alice", "Bob"}; Array of pointers to string literals, accessed as const data

A two-dimensional character array stores the characters directly in its rows. An array of pointers stores addresses instead, so its strings may have different lengths and may be stored in different locations.

When reading user input into a row, the input operation must not write beyond that row’s capacity.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *