双指针数组的功能不起作用

Functions of double pointer array doesn't work

我写了这段代码:

#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 打印 arrPP 指向的所有数组,并且 maxLengthString(char **arrPP[] ) 应该 return 最长的数组。 我无法 return 最长的数组,所以我尝试打印长度的最大值。 输出应该是:

father mother
sister brother grandfather
grandmother
uncle aunt
3

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

但没有打印任何内容,这是为什么?我怎么能 return 最长的数组?

条件 **p != NULL**c != NULL 是错误的,它们可以在不检查的情况下取消引用 NULL。它们应该是 *p != NULL*c != NULL 以检查 pc 指向的内容是否是 NULL.

此外,调用函数 maxLengthStringprintAllStrings 的顺序应该交换以获得所需的输出。

对于初学者来说,两个 for 循环

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

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

不正确。传递给函数数组的元素具有 char ** 类型。因此循环中的条件应类似于

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

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

还有这个 while 循环中的 if 语句

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

必须移到循环外

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

你应该在 printf

的调用中添加换行符 '\n'
printf("%d\n", max);