Functions of double pointer array doesn't work

Viewed 64

I wrote this code:

#include <stdio.h>

void printAllStrings(char **arrPP[])
{
    for (char ***p = arrPP; **p != NULL; ++p)
    {
        int z = 0;
        while (*(*p + z) != NULL)
        {
            printf("%s ", *(*p + z));
            z++;
        }
        putchar('\n');
    }
}
void maxLengthString(char **arrPP[])
{
    int max = 0;
    for (char ***c = arrPP; **c != NULL; ++c)
    {
        int counter = 0;
        int z = 0;
        while (*(*c + z) != NULL)
        {
            counter++;
            z++;
            if (counter > max)
                max = counter;
        }
    }
    printf("%d", max);
}

int main()
{
    char *arrP1[] = {"father", "mother", NULL};
    char *arrP2[] = {"sister", "brother", "grandfather", NULL};
    char *arrP3[] = {"grandmother", NULL};
    char *arrP4[] = {"uncle", "aunt", NULL};
    char **arrPP[] = {arrP1, arrP2, arrP3, arrP4, NULL};

    maxLengthString(arrPP);
    printAllStrings(arrPP);
    return 0;
}

printAllStrings prints all the arrays that arrPP points at and maxLengthString(char **arrPP[] )should return the longest array. I couldd't return the longest array so I tried to print the max value of length. the output should be:

father mother
sister brother grandfather
grandmother
uncle aunt
3

or

father mother
sister brother grandfather
grandmother
uncle aunt
arrP2 // cause it's the longest array

but nothing is printed why is that?And how could I return the longest array?

2 Answers

The conditions **p != NULL and **c != NULL are wrong and they can dereference NULL without checking. They should be *p != NULL and *c != NULL to check if what are pointed at by p and c are NULL.

Also the order to call the functions maxLengthString and printAllStrings should be swapped to get the desired output.

For starters the both for loops

for (char ***p = arrPP; **p != NULL; ++p)

and

for (char ***c = arrPP; **c != NULL; ++c)

are incorrect. Elements of the passed to the functions arrays have the type char **. Thus conditions in the loops shall look like

for (char ***p = arrPP; *p != NULL; ++p)

and

for (char ***c = arrPP; *c != NULL; ++c)

Also the if statement within this while loop

    while (*(*c + z) != NULL)
    {
        counter++;
        z++;
        if (counter > max)
            max = counter;
    }

must be moved outside the loop

    while (*(*c + z) != NULL)
    {
        counter++;
        z++;
    }
    if (counter > max)
        max = counter;

And you should add the new line character '\n' in this call of printf

printf("%d\n", max);
Related