Skip to content

← Back to C Course Foundations

Two-Dimensional Character Array (C)

Learning Objectives

  • Declare and initialize 2D character arrays.
  • Search strings in an array.
  • Perform copy, merge, and length operations.

Concept

A 2D character array like char names[5][20] stores 5 strings, each up to 19 characters plus \0.

Algorithm (Search Name)

  1. Store n names in names[n][maxLen].
  2. Read target string.
  3. Compare each entry with target.
  4. Print index if found, else "not found".

C Example

#include <stdio.h>
#include <string.h>

int main(void) {
    char names[4][20] = {"Asha", "Ravi", "Kiran", "Mina"};
    char target[20] = "Kiran";
    int found = -1;

    for (int i = 0; i < 4; i++) {
        if (strcmp(names[i], target) == 0) {
            found = i;
            break;
        }
    }

    if (found >= 0) {
        printf("Found at index %d\n", found);
    } else {
        printf("Not found\n");
    }

    char copy[20];
    strcpy(copy, names[1]);
    printf("Copied: %s\n", copy);

    char merged[40];
    strcpy(merged, names[0]);
    strcat(merged, "-");
    strcat(merged, names[2]);
    printf("Merged: %s\n", merged);

    printf("Length of %s = %lu\n", names[3], strlen(names[3]));
    return 0;
}

Dry Run

  • Target Kiran
  • Compare with Asha -> no
  • Compare with Ravi -> no
  • Compare with Kiran -> yes, index 2

Common Mistakes

  • Not leaving space for null terminator.
  • Using == instead of strcmp for string comparison.
  • Buffer overflow during copy/merge.

Practice

  1. Search multiple targets.
  2. Merge all names into one string.
  3. Sort names alphabetically.