c -遍历指针的指针数组



我想遍历**list_arg[]

我不能让这个工作,除非我尝试在另一个函数中迭代它,然后我可以做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;
}

当使用指针数组(特别是指针指向指针的数组)时,通常最好使用特定的[]操作符,而不是试图找出哪种解引用(*)操作符的组合将到达(并操作)所需的目标。

下面的代码完成了(我认为)您想要的(我为其中一个数组添加了一个额外的名称,以显示迭代确实有效):

#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;
}

如果使用指针代替数组,可以进行迭代。

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

或不带复合字面值:

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;
}