在c99模式之外循环静态分配的数组?

ran*_*its 1 c loops c99

这是参考发布的解决方案: 循环固定大小的数组,而不在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)

bal*_*pha 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;

}
Run Code Online (Sandbox Code Playgroud)


sth*_*sth 6

  1. 您的循环变量it是类型char*,数组的内容是类型const char*.如果你改变it也是一个const char*警告应该消失.

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