Back to course

Array of Strings (2D Character Arrays)

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 33: Array of Strings (2D Character Arrays)

An array of strings is represented in C as a 2D character array, where each row holds one string (character array), terminated by \0.

Declaration and Initialization

Syntax: char array_name[number_of_strings][max_length_of_string];

c // 4 strings, maximum length 10 characters (plus null terminator) char names[4][11] = { "Alice", // 6 bytes (5 + \0) "Bob", // 4 bytes "Charlie", // 8 bytes "Dave" // 5 bytes };

Accessing and Iterating

  • names[i] refers to the entire string (the row).
  • names[i][j] refers to the j-th character of the i-th string.

Example: Printing all names

c #include <stdio.h> #define NUM_NAMES 4 #define MAX_LEN 11

int main() { char names[NUM_NAMES][MAX_LEN] = {"Alice", "Bob", "Charlie", "Dave"};

for (int i = 0; i < NUM_NAMES; i++) {
    // Use %s to print the entire row (string)
    printf("Name %d: %s\n", i + 1, names[i]);
}

// Accessing a specific character (the 'r' in Charlie)
printf("Char: %c\n", names[2][3]); 
return 0;

}

Alternative: Array of Pointers to Strings (Preview)

A more flexible and memory-efficient way to handle strings is using an array of pointers, where each pointer points to a string literal stored elsewhere (covered later in the pointers module).