for循环中的数组由于某种原因不起作用

Array in for-loop is not working for some reason

我不明白为什么语法正确时无法编译:

int arrows[1] = {23};
    for(arrows[1]; arrows[1] < 300; arrows[1]++)
    {
      cout << arrows[1];
    }

错误:

error: expected unqualified-id before 'for' !!

error: 'arrows' does not name a type !!

error: 'arrows' does not name a type

我正在使用 this online compiler (x86 GCC 4.9.2)。

在声明数组时指定其大小,这就是为什么在您的情况下 1 是正确的,如果您想要一个大小为 1 的数组。

访问数组元素时需要使用从 0 开始的索引。因此,要访问数组的第一个元素,您将使用 0.

您的代码将如下所示

#include <iostream>

int main()
{
    int arrows[1] = {23};

    for(arrows[0]; arrows[0] < 300; arrows[0]++)
    {
        std::cout << arrows[0];
    }

    return 0;
}

我认为交互式编译器坏了。它甚至失败了:

for(;;) {
}

编辑:我错了……你不能只把代码放在那里,添加一个 main 函数就可以了。

#include <iostream>    
int main( int argc, const char* argv[] )
{
    int arrows[1] = {23};
    for(arrows[1]; arrows[1] < 300; arrows[1]++)
    {
        std::cout << arrows[1];
    }
}

我认为用这个在线编译器学习不是正确的方法...

此代码在 "normal" 开发环境下运行。

#include<iostream>

using namespace std;


int main()
{
    int arrows[1] = { 23 }; // initialize array of size one and assign it value 23
    // sizeof(arrows)/sizeof(*arrows) calculates the length of an array
    // iterate through all elements of the array and display their values..
    for (int i = 0; i < sizeof(arrows) / sizeof(*arrows); i++)
    {
        cout << arrows[i];
    }
    return 0;
}