【问题标题】:Functions of double pointer array doesn't work双指针数组的功能不起作用
【发布时间】:2021-09-01 13:57:42
【问题描述】:

我写了这段代码:

#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[] ) 应该返回最长的数组。 我无法返回最长的数组,所以我尝试打印长度的最大值。 输出应该是:

father mother
sister brother grandfather
grandmother
uncle aunt
3

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

但是什么都没有打印为什么会这样?我怎么能返回最长的数组?

【问题讨论】:

    标签: arrays c for-loop pointers dereference


    【解决方案1】:

    条件**p != NULL**c != NULL 是错误的,它们可以取消引用NULL 而无需检查。它们应该是*p != NULL*c != NULL,以检查pc 指向的内容是否为NULL

    还应交换调用函数maxLengthStringprintAllStrings 的顺序以获得所需的输出。

    【讨论】:

      【解决方案2】:

      对于初学者来说,两个 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);
      

      【讨论】:

        猜你喜欢
        • 2013-10-12
        • 1970-01-01
        • 1970-01-01
        • 2021-06-18
        • 1970-01-01
        • 2020-11-22
        • 1970-01-01
        • 2020-10-11
        • 1970-01-01
        相关资源
        最近更新 更多