Vishal Kumar Gourav
Vishal Kumar Gourav

Reputation: 19

Array of array of strings in C

In C, in a array that looks something like

{{"gsga","baf"},{"ad","aasb","asdf","asdfsd"},{"ads","sd","sd"}}

How to get different types of lengths such as:

Upvotes: 0

Views: 3582

Answers (2)

David Ranieri
David Ranieri

Reputation: 41017

You can get the size of all dimensions (3 x 4 x 7) using the sizeof operator.

If you want to know the length of the last one, use strlen in a loop:

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

int main(void)
{
    char data[][4][7] = {{"gsga","baf"},{"ad","aasb","asdf","asdfsd"},{"ads","sd","sd"}};
    size_t items1 = sizeof data / sizeof data[0]; /* size of dim 1 */
    size_t items2 = sizeof data[0] / sizeof data[0][0]; /* size of dim 2 */
    size_t iter1, iter2, count, len;

    printf("%zu items\n", items1);
    for (iter1 = 0; iter1 < items1; iter1++) {
        count = 0;
        printf("Item %zu\n", iter1);
        for (iter2 = 0; iter2 < items2; iter2++) {
            len = strlen(data[iter1][iter2]); /* size of dim 3 */
            if (len > 0) {
                printf("\tSubitem %zu: %zu characters\n", iter2, len);
                count++;
            }
        }
        printf("\t%zu subitems\n", count);
    }
    return 0;
}

Output:

3 items
Item 0
    Subitem 0: 4 characters
    Subitem 1: 3 characters
    2 subitems
Item 1
    Subitem 0: 2 characters
    Subitem 1: 4 characters
    Subitem 2: 4 characters
    Subitem 3: 6 characters
    4 subitems
Item 2
    Subitem 0: 3 characters
    Subitem 1: 2 characters
    Subitem 2: 2 characters
    3 subitems

data can be also declared as

char *data[][4] = {{"gsga","baf"},{"ad","aasb","asdf","asdfsd"},{"ads","sd","sd"}};

But then you need to check for NULL's to get the number of (non empty) subitems:

    for (iter2 = 0; iter2 < items2; iter2++) {
        if (data[iter1][iter2] != NULL) {
            len = strlen(data[iter1][iter2]);
            ...
        }
    }

Full Code

Upvotes: 4

August Karlstrom
August Karlstrom

Reputation: 11377

The following program prints the values you mention:

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

#define LEN(arr) ((int) (sizeof (arr) / sizeof (arr)[0]))

int main(void)
{
    const char *A[][4] = {{"gsga", "baf"}, {"ad", "aasb", "asdf", "asdfsd"}, {"ads", "sd", "sd"}};

    printf("%d\n", LEN(A)); /*number of rows*/
    printf("%d\n", LEN(A[0])); /*number of columns*/
    printf("%d\n", (int) strlen(A[1][1]) + 1); /*size of element*/
    return 0;
}

Upvotes: 0

Related Questions