C Array of Strings

To store many names we need an array of strings. In C there are two common ways.

Way 1: 2D char array

Each row is one string. All rows have the same fixed size.

#include <stdio.h>

int main(void) {
    char names[3][10] = {"Robin", "Maria", "John"};

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

Output:

Output of the above program is

Robin
Maria
John

The size 10 means each name can have up to 9 characters, plus the null character. Short names waste some space.

Way 2: array of pointers

Each element points to a string. There is no waste of space, but the strings are read only.

#include <stdio.h>

int main(void) {
    const char *cities[] = {"Delhi", "Mumbai", "Pune", "Jaipur"};
    int n = sizeof(cities) / sizeof(cities[0]);

    for (int i = 0; i < n; i++) {
        printf("%d. %s\n", i + 1, cities[i]);
    }
    return 0;
}

Output:

Output of the above program is

1. Delhi
2. Mumbai
3. Pune
4. Jaipur

Find the longest name

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

int main(void) {
    char names[4][12] = {"Asha", "Vikram", "Neha", "Maria"};
    int longest = 0;

    for (int i = 1; i < 4; i++) {
        if (strlen(names[i]) > strlen(names[longest])) {
            longest = i;
        }
    }
    printf("Longest: %s\n", names[longest]);
    return 0;
}

Output:

Output of the above program is

Longest: Vikram

Read names from the user

#include <stdio.h>

int main(void) {
    char names[2][20];

    for (int i = 0; i < 2; i++) {
        scanf("%19s", names[i]);
    }
    printf("%s and %s\n", names[0], names[1]);
    return 0;
}

Output:

Output of the above program is

Asha
Vikram
Asha and Vikram

Note: Use strcpy(names[i], "text") to put a new value in a 2D array row. You cannot use = for strings.

Next: C Pointers.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.