1

这是参考发布的解决方案: Looping a fixed size array without defined its size in 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
4

5 回答 5

7

除了 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;

}
于 2009-12-28T14:40:11.467 回答
6
  1. 你的循环变量it是 type char*,数组的内容是 type const char*。如果您更改it为也是一个const char*警告应该消失。

  2. it在 for 语句中声明,这在 C99 之前的 C 中是不允许的。而是it在开头声明。 或者,您可以添加或添加到您的 gcc 标志以启用 C99 语言功能。main()
    -std=c99-std=gnu99

于 2009-12-28T14:36:30.977 回答
1

编译代码时使用-std=c99选项以使用这些C99功能。

更改itconst char*类型(以删除警告)

于 2009-12-28T14:36:11.180 回答
0

在 C99 之前,在 for 循环中声明该字符指针是非标准的。

于 2009-12-28T14:36:08.013 回答
0

您需要做两件事才能在没有警告的情况下进行编译:声明迭代器const char* it,并在函数的开头而不是在循环语句中进行。

于 2009-12-28T14:36:22.927 回答