← 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)¶
- Store
nnames innames[n][maxLen]. - Read target string.
- Compare each entry with target.
- 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, index2
Common Mistakes¶
- Not leaving space for null terminator.
- Using
==instead ofstrcmpfor string comparison. - Buffer overflow during copy/merge.
Practice¶
- Search multiple targets.
- Merge all names into one string.
- Sort names alphabetically.