Array of array of strings in C

Array of array of strings in C

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 itemsn, items1);
    for (iter1 = 0; iter1 < items1; iter1++) {
        count = 0;
        printf(Item %zun, iter1);
        for (iter2 = 0; iter2 < items2; iter2++) {
            len = strlen(data[iter1][iter2]); /* size of dim 3 */
            if (len > 0) {
                printf(tSubitem %zu: %zu charactersn, iter2, len);
                count++;
            }
        }
        printf(t%zu subitemsn, 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 NULLs 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

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(%dn, LEN(A)); /*number of rows*/
    printf(%dn, LEN(A[0])); /*number of columns*/
    printf(%dn, (int) strlen(A[1][1]) + 1); /*size of element*/
    return 0;
}

Array of array of strings in C

Leave a Reply

Your email address will not be published. Required fields are marked *