【问题标题】:How do I iterate over a pointer to a pointer?如何遍历指向指针的指针?
【发布时间】:2011-07-10 14:14:36
【问题描述】:

假设我有以下变量:

char c[] = "ABC";
char *ptr = &c;
char **ptr2 = &ptr;

我知道我可以通过这种方式遍历指向 char 数组的指针:

int i;
for(i=0; i<3; i++){
    printf("TEST******************, %c\n", ptr[i]);
}

如何遍历指向指针的指针?

【问题讨论】:

  • 仅供参考:&amp;cchar (*)[4] 类型的值(指向 4 个字符的数组的指针):c 不会衰减到指向表达式 @ 中其第一个元素的指针987654326@。您的编译器应该警告分配中不兼容的类型...

标签: c string pointers char


【解决方案1】:

假设:

  6   char c[] = "ABC";
  7 
  8   char *ptr   = &c;
  9   char *ptr2  = ptr;       
 10   char **ptr3 = &ptr;   

在这种情况下:

  • ptr 表示 c 的地址
  • ptr2 代表ptr 的地址。 指向指针的指针
  • ptr3 是一个,存储在ptr 中,即c 的地址。

**ptr3=&amp;ptr 表示 - 获取ptr 的地址,查看内部并将其值(不是地址)分配给ptr3

如果我正确理解了您的问题,您需要在我的示例中使用指向指针的指针:ptr2 而不是 ptr3

如果是这样,您可以访问以下元素:

ptr2[0] = A
ptr2[1] = B
ptr2[2] = C

为了记录,以下将产生相同的结果。试试看。

 12   printf ("===>>> %x\n", ptr2);
 13   printf ("===>>> %x\n", *ptr3);

供您参考的好讨论是here

【讨论】:

    【解决方案2】:

    你的例子:

    int i;
    for(i=0; i<3; i++){
        printf("TEST******************, %c\n", (*ptr2)[i]);
    }
    

    【讨论】:

      【解决方案3】:

      如果我没有误解你的问题,这段代码应该可以工作

      printf("TEST******************, %c\n", (*ptr2)[i]);
      

      【讨论】:

        【解决方案4】:

        让我举个例子,

        char **str; // double pointer declaration
        str = (char **)malloc(sizeof(char *)*2);
        str[0]=(char *)"abcdefgh";   // or *str  is also fine instead of str[0]
        str[1]=(char *)"lmnopqrs";
        
        while(*str!=NULL)
        {
            cout<<*str<<endl; // prints the string
            str++;
        }
        free(str[0]);
        free(str[1]);
        free(str);
        

        或另一个您可以理解的最佳示例。 这里我使用了 2 个 for 循环,因为我正在遍历字符串数组的每个字符。

        char **str = (char **)malloc(sizeof(char *)*3); // it allocates 8*3=24 Bytes
        str[0]=(char *)"hello";    // 5 bytes 
        str[1]=(char *)"world";    // 5 bytes
        // totally 10 bytes used out of 24 bytes allocated
        while(*str!=NULL)   // this while loop is for iterating over strings
        {
            while(**str!=NULL)   // this loop is for iterating characters of each string
            {
                 cout<<**str;
            }
            cout<<endl;
            str++;
        }
        free(str[0]);
        free(str[1]);
        free(str);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-05-29
          • 2015-08-12
          • 1970-01-01
          • 2021-11-23
          • 1970-01-01
          • 2017-03-19
          相关资源
          最近更新 更多