Home > database >  Iterate through an array of pointer of pointers
Iterate through an array of pointer of pointers

Time:07-15

I want to iterate through **list_arg[].

I can't make this work, unless I try to iterate through it in another function, then I can do list_arg .

int main(int argc, char *argv[]) {
    char *three[] = {"Ver", NULL}
    char *two[] = {"john", NULL};
    char *one[] = {"Majka", NULL};
    char **list_arg[] = { one, two, three, NULL};

   while (**list_arg != NULL) {
       printf("%s", **list_arg);
       list_arg  ; //invalid increase
       //(*list_arg)  ; iterates through one[] only.
       //(**list_arg)  ; iterates through *one[], aka "Majka" only.
   }
   return 0;
}

CodePudding user response:

When using arrays of pointers (and especially arrays of pointers to pointers), it is generally better to use the specific [] operator, rather than trying to work out which combination of dereferencing (*) operators will get to (and manipulate) the required target.

The following code does what (I think) you want (I have added an extra name to one of the arrays, to show that the iteration does work):

#include <stdio.h>

int main()
{
    char* three[] = { "Ver", NULL };
    char* two[] = { "John", "Fred", NULL}; // Add extra one here for demo
    char* one[] = { "Majka", NULL };
    char** list_arg[] = {one, two, three, NULL};

    for (size_t i = 0; list_arg[i] != NULL;   i) {
        char** inner = list_arg[i];
        for (size_t j = 0; inner[j] != NULL;   j) {
            printf("%s ", inner[j]);
        }
        printf("\n"); // New line to separate inner arrays
    }
    return 0;
}

CodePudding user response:

You can iterate if you use pointer instead array.

int main(int argc, char *argv[])
{
    char *three[] = {"Ver", NULL};
    char *two[] = {"john", NULL};
    char *one[] = {"Majka", NULL};
    char ***list_arg = (char **[]){ one, two, three, NULL};

    while(*list_arg)
    {
        while(**list_arg)
        {
            while(***list_arg)
            {
                fputc(***list_arg, stdout);
                (**list_arg)  ;
            }
            putc('\n', stdout);
            (*list_arg)  ;
        }
        list_arg  ;
    }

   return 0;
}

https://godbolt.org/z/Y3benvWja

or without compound literals:

int main(int argc, char *argv[])
{
    char *three[] = {"Ver", NULL};
    char *two[] = {"john", NULL};
    char *one[] = {"Majka", NULL};
    char **list_arg_array[] = { one, two, three, NULL};
    char ***list_arg = list_arg_array;

    while(*list_arg)
    {
        while(**list_arg)
        {
            while(***list_arg)
            {
                fputc(***list_arg, stdout);
                (**list_arg)  ;
            }
            putc('\n', stdout);
            (*list_arg)  ;
        }
        list_arg  ;
    }

   return 0;
}
  • Related