c - 递增指向 C 中指针的指针

标签 c arrays loops pointers while-loop

<分区>

我一直在用 C 浏览 Kernighan 和 Ritchie 的书,并且迷失在指向指向 char 数组的指针的指针中。

让我们来看这个示例代码:

char str1[] = "This ";
char str2[] = "is ";
char str3[] = "a cat.";

char *ptr1 = str1;
char *ptr2 = str2;
char *ptr3 = str3;

char *ptrall[] = { ptr1, ptr2, ptr3 };

问题: 我如何使用 while 打印所有数组?

这本书告诉我(引述):

while (...){
   printf("%s\", *ptr++);}

因此,这个*ptr++ 应该在**ptr 中递增指针。但是当我尝试在 VS 中构建它时,它说存在“左值”错误。

我在这里误解了什么?我应该如何增加存储在 ** 中的指针? 我仅限于 printf("%s", ptr[i++]) 吗?

最佳答案

Question: How do I print all of the arrays using, say, while?

这取决于数组 ptrall 是如何定义的。

如果数组ptrall定义如下

char *ptrall[] = { ptr1, ptr2, ptr3, NULL };

然后可以使用while循环按如下方式输出

#include <stdio.h>

int main( void )
{
    char str1[] = "This ";
    char str2[] = "is ";
    char str3[] = "a cat.";

    char *ptr1 = str1;
    char *ptr2 = str2;
    char *ptr3 = str3;

    char *ptrall[] = { ptr1, ptr2, ptr3, NULL };

    char **ptr = ptrall;

    while (*ptr) printf("%s", *ptr++);
    putchar('\n');

    return 0;
}

程序输出为

This is a cat.

如果数组 ptrall 被定义为你的问题,就像

char *ptrall[] = { ptr1, ptr2, ptr3 };

然后可以使用while循环按如下方式输出

#include <stdio.h>

int main( void )
{
    char str1[] = "This ";
    char str2[] = "is ";
    char str3[] = "a cat.";

    char *ptr1 = str1;
    char *ptr2 = str2;
    char *ptr3 = str3;

    char *ptrall[] = { ptr1, ptr2, ptr3 };

    char **ptr = ptrall;

    while (ptr != ptrall + sizeof( ptrall ) / sizeof( *ptrall ) ) printf("%s", *ptr++);
    putchar('\n');

    return 0;
}

程序输出与上图相同。

至于这次调用中使用的表达方式

printf("%s", *ptrall++); 

那么数组指示符是不可修改的左值。您不能将预增量和后增量运算符应用于数组指示符。

关于c - 递增指向 C 中指针的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47797584/

相关文章:

php - 如何在 while 循环中只打印一次帖子?

Python - 制作计数器,制作循环?

c - 注意: expected ‘char * __restrict__’ but argument is of type ‘int8_t *’

python - 与 numpy 对象数组相比,列表列表在速度方面有哪些优点/缺点?

将 C 转换为具有分段问题的 NASM 程序集

c - ASM 访问 c 结构的动态二维数组

java - 如何向数组中随机插入String数字-Java

javascript - 获取字符串中重复子串的列表

c - 这两个 C 声明之间有什么区别?

c - Oracle Pro*C — 在嵌套循环中使用游标