这是参考发布的解决方案: 循环固定大小的数组,而不在C中定义其大小
这是我的示例代码:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
static const char *foo[] = {
"this is a test",
"hello world",
"goodbye world",
"123",
NULL
};
for (char *it = foo[0]; it != NULL; it++) {
printf ("str %s\n", it);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
试图编译这个给出:
gcc -o vararray vararray.c
vararray.c: In function ‘main’:
vararray.c:14: warning: initialization discards qualifiers from pointer target type
vararray.c:14: error: ‘for’ loop initial declaration used outside C99 mode
Run Code Online (Sandbox Code Playgroud)
除了for循环中的初始化之外,你在错误的地方递增.我认为这就是你的意思(请注意,我不是一个C大师):
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
static const char *foo[] = {
"this is a test",
"hello world",
"goodbye world",
"123",
NULL
};
const char **it;
for (it=foo; *it != NULL; it++) {
printf ("str %s\n", *it);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您的循环变量it
是类型char*
,数组的内容是类型const char*
.如果你改变it
也是一个const char*
警告应该消失.
你it
在for语句中声明,在C99之前的C中不允许这样做.it
在开始时声明main()
.
或者,您可以添加-std=c99
或添加-std=gnu99
到gcc标志以启用C99语言功能.