题
这是在提到一个解决方案张贴在: 循环的一个固定的尺寸阵列,但没有界定其大小在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;
}
试图编纂这给:
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
解决方案
除了在初始化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;
}
其他提示
你的循环变
it
的类型char*
, 内容的阵列的类型const char*
.如果你改变it
也是一个const char*
警告应该去掉。你声明
it
内对声明,这是不允许在C之前C99。声明it
在开始main()
代替。
或者你可以加入-std=c99
或-std=gnu99
给你的海湾合作委员会标志以使C99语言特征。
编译代码才能使用-std=c99
功能使用C99
选项时,点击
更改it
到const char*
类型(除去警告)
C99之前,声明字符指针在for循环是非标准的。
您需要两样东西有此编译没有警告:申报迭代const char* it
,并在函数的开始做,而不是在循环语句
不隶属于 StackOverflow