我一直在用 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++);
那么数组指示符是不可修改的左值。您不能将预增量和后增量运算符应用于数组指示符。