String Arrays in C

A string array can store several C strings. One common form is a two-dimensional character array where each row has space for one null-terminated string.

Store and Display Several Names Top ↑

#include <stdio.h>

int main(void) {
    char names[4][20] = {"Alex", "Roan", "Allen", "Roman"};

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

    return 0;
}

Output

Alex
Roan
Allen
Roman

Read Full Names Safely Top ↑

The old gets() function is unsafe and was removed from the C standard. Use fgets() with the size of each row.

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

int main(void) {
    char names[4][40];

    for (int i = 0; i < 4; i++) {
        printf("Enter name %d: ", i + 1);

        if (fgets(names[i], sizeof names[i], stdin) == NULL) {
            printf("Input error.\n");
            return 1;
        }

        names[i][strcspn(names[i], "\n")] = '\0';
    }

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

    return 0;
}

How the Dimensions Work Top ↑

char names[4][40];
  • 4 = number of strings.
  • 40 = maximum storage available for each string, including its null terminator.




plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer